React - 通过单击按钮获取输入的值

MrF*_*ndo 5 reactjs react-dom

我需要实现一个搜索按钮来搜索输入的值。我知道如何向按钮添加 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>
  );
}
Run Code Online (Sandbox Code Playgroud)

这是我尝试过的。我在google上找到的一行代码。我明白了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>
  );
}
Run Code Online (Sandbox Code Playgroud)

Zin*_*nho 2

你可以做的是创建一个handleChangeon input,每次输入改变时,状态就会改变......所以当你运行时handleSubmit,你只需要获取状态

function App() {
  const [inputValue, setInputValue] = useState('')

  function handleSearch(e) {
    // here you can get the inputValue
     DoWhateverIWantWithSearchValue(inputValue)
  }

  return (
    <Container className="my-4">
      <input type="text" handleChange={(e) => setInputValue(e.target.value)} ></input>
      <button onClick={handleSearch}>search</button>
    </Container>
  );
}
Run Code Online (Sandbox Code Playgroud)