如何在无状态 React 组件中单击按钮获取输入值?

Aam*_*han 11 reactjs

我有以下功能组件

const input = props => (
  <div>
    <input placeholder="Type a message..." />
    <div onClick={props.send} className="icon">
      <i className="fa fa-play" />
    </div>
  </div>
)
Run Code Online (Sandbox Code Playgroud)

我怎么可能将输入的值传递给props.send()?

Aam*_*han 19

我在 React 的官方文档中找到了针对这种情况的解决方案:https : //reactjs.org/docs/refs-and-the-dom.html#refs-and-functional-components

这种方法允许您的组件保持无状态,并且不需要您在每次更改时更新父组件。

基本上,

const input = props => {

let textInput = React.createRef();

function handleClick() {
  console.log(textInput.current.value);
}

return (
    <div>
      <input ref={textInput} placeholder="Type a message..." />
      <div onClick={handleClick} className="icon">
        <i className="fa fa-play" />
      </div>
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

2021 年 5 月编辑:由于这个答案似乎引起了一些关注,因此我也更新了答案以使用基于钩子的方法,因为这就是我现在要使用的(如果使用 React 16.8 及更高版本)。

const input = props => {  
  const [textInput, setTextInput] = React.useState('');

  const handleClick = () => {
    console.log(textInput);
    props.send(textInput);
  }

  const handleChange = (event) => {
    setTextInput(event.target.value);
  }

  return (
    <div>
      <input onChange={handleChange} placeholder="Type a message..." />
      <div onClick={handleClick} className="icon">
        <i className="fa fa-play" />
      </div>
    </div>
  )
}
Run Code Online (Sandbox Code Playgroud)

  • @CaleSwitzer,您现在也可以使用钩子。我现在可能会使用这种方法。 (3认同)