首页 > 解决方案 > Material UI 搜索栏 - 使用钩子设置查询状态

问题描述

我是 React 的新手。我正在尝试使用该组件实现搜索栏:

https://www.npmjs.com/package/material-ui-search-bar

我目前的代码是:

function Searchbar() {

  const [finalQuery, setQuery] = useState("");


    return(
        <SearchBar              
            onChange={(event) => console.log(event)}
            onRequestSearch={() => setQuery(#Update the state so that it reflects the query the user wrote)}
            style={{
                marginTop: 200,
                marginLeft: 'auto',
                marginRight: 'auto',
                maxWidth: 800,
                }}
        />
    )
}

我不清楚如何传递给setQuery最终搜索的值(当用户按下回车键时)以便finalQuery更新状态。

例如,如果我这样做:

onRequestSearch={() => setQuery(console.log("trytry"))}

当我按下回车键时,在控制台中我得到trytry了,所以我假设状态finalQuery已正确更新。但我怎样才能动态地做到这一点?

然后,最终查询将被发送到 API。

标签: reactjs

解决方案


每次文本更改时都会调用 onChange,因此更新查询的正确位置在 onChange

return (
<SearchBar
    value={finalQuery}
    onChange={(newValue) => setQuery(newValue)}
    onRequestSearch={() => doSomethingWith(query)}
/>
)

推荐阅读