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

标签 reactjs

我有以下功能组件

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

如何将输入值传递给 props.send()

最佳答案

我在 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>
  )
}
<小时/>

2021 年 5 月编辑:由于这个答案似乎引起了一些关注,我也更新了答案以使用基于钩子(Hook)的方法,因为这就是我现在使用的方法(如果使用 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>
  )
}

关于reactjs - 如何在无状态 React 组件中单击按钮时获取输入值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52028418/

相关文章:

javascript - 在 typescript 中给响应一种获取响应?

ios - 为什么我们在react-native中使用ProgressViewIOS组件的progressImage属性?

javascript - 以 React 方式在 HTML 中包装多个字符串

javascript - 如何使用 Webpack 2 热重载 Sass?

javascript - ReactJS - 将对象数组的元素作为 Prop 传递

reactjs - Apollo 客户端延迟重新获取

reactjs - React 应用程序托管在 s3 意外 token 上 <

reactjs - 使用 useSelector react-redux 钩子(Hook)重新选择 - 状态未定义

javascript - 'GET_LIST' 的 dataProvider 可能是错误的

javascript - 如何在react中显示来自api的数据