reactjs - 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。
解决方案
每次文本更改时都会调用 onChange,因此更新查询的正确位置在 onChange
return (
<SearchBar
value={finalQuery}
onChange={(newValue) => setQuery(newValue)}
onRequestSearch={() => doSomethingWith(query)}
/>
)
推荐阅读
- python - PythonAnywhere 上 Flask 的日志记录格式
- android - Firebase - 获取所有孩子并添加到 ListView
- android - Visual Studio 2013 的目标 Android 版本中未显示已安装的 API 版本 28 (Pie)
- dictionary - TypeError:无法调用 null 的方法“getRange”。(第 25 行,文件“代码”)
- python-3.x - 从 np 数组创建 geoTiff gdal
- python - tf.placeholder(tf.random_normal([3,1]), name='weight') -> 错误
- jquery - 如何使用 jquery 在同一功能上使用 select 和 keyup 事件?
- php - Lumen MySQL`QueryException`错误:SQLSTATE [HY000] [2002] php_network_getaddresses:getaddrinfo失败:名称或服务未知
- c++ - GNU LD 链接器 - 无法在地址处获取闪存中的变量
- sql-server - 更改表添加位列以防万一