【问题标题】:How to get the TextField value with onclick button event React Material UI如何使用 onclick 按钮事件 React Material UI 获取 TextField 值
【发布时间】:2021-09-12 01:43:24
【问题描述】:

我正在尝试获取搜索文本字段的输入值,然后单击“搜索”按钮,使用搜索输入调用 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 它时,我得到一个空数组。有什么建议吗?

【问题讨论】:

  • inputRef={searchForm} 是不必要的,使用onChange 并将值设置为您的状态

标签: javascript reactjs react-hooks material-ui


【解决方案1】:

您需要在 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
          >

然后使用变量进行搜索。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-03
    • 1970-01-01
    • 2020-12-20
    相关资源
    最近更新 更多