我试图获取搜索文本字段的输入值,然后单击“搜索”按钮,使用搜索输入调用 API。这是我到目前为止所拥有的:
const handleSearchSubmit = async () => {
setSearchTerm(searchForm.current.value)
console.log(searchTerm)
const fetchSearch = async () => {
const params = {searchTerm: searchTerm}
console.log(params)
const response = await axios("/api/search", { params });
const data = response.data
setResTable(data)
console.log(resTable)
};
fetchSearch();
};
<TextField
id="searchInput"
inputRef={searchForm}
style={{ margin: 8 }}
placeholder="Enter a code or procedure"
fullWidth
/>
</FormGroup>
</Col>
<Button variant="contained" color="primary" onClick={handleSearchSubmit}>
Search
</Button>
我似乎无法获取 TextField 输入的值。当我 console.log 时,我得到一个空数组。有什么建议吗?
最佳答案
您需要在 TextField 中使用 onChange。
创建一个状态变量并在 onChange 中设置它。
<TextField
id="searchInput"
inputRef={searchForm}
onChange={(v) => setValue(v.target.value) } //Add your setVariable to this line
style={{ margin: 8 }}
placeholder="Enter a code or procedure"
fullWidth
>
然后使用该变量进行搜索。
关于javascript - 如何通过 onclick 按钮事件 React Material UI 获取 TextField 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68185607/