我需要实现一个搜索按钮来搜索输入的值。我知道如何添加 onClick listener
(这是名字吗?)按钮,以便它 fires
(这是表达式吗?)一个函数。
但是在函数内,我不知道如何get
输入值。
这是我得到的:
function App() {
const [query, setQuery] = useState('')
const [page, setPage] = useState(1)
const { jobs, loading, error } = useFetchJobs(query, page)
function handleSearch(e) {
setQuery(???)
setPage(1)
}
return (
<Container className="my-4">
<input type="text"></input>
<button onClick={handleSearch}>search</button>
</Container>
);
}
这是我尝试过的。我在谷歌上找到的一行代码。我收到 Error: Function components cannot have string refs
function App() {
function handleSearch(e) {
setQuery(React.findDOMNode(this.refs.search).value.trim())
setPage(1)
}
return (
<Container className="my-4">
<input type="text" ref="search" ></input>
<button onClick={handleSearch}>search</button>
</Container>
);
}
最佳答案
首先将输入的值设置为query
(初始值将为空,因为我们在 useState
中设置了该值)然后在更改输入值时我们将输入值设置为 setQuery
使用 onChange 方法,现在您可以使用 query
搜索的值(value)
function App() {
const [query, setQuery] = useState('')
const [page, setPage] = useState(1)
const { jobs, loading, error } = useFetchJobs(query, page)
function handleSearch(e) {
\\**write your search function here with query value**
}
return (
<Container className="my-4">
<input value={query} onChange={(e)=>setQuery(e.target.value)} type="text"></input>
<button onClick={handleSearch}>search</button>
</Container>
);
}
关于reactjs - React - 通过单击按钮获取输入的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64403034/