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 - React-Material-ui : Autocomplete on words that aren't the first in a sentence

javascript - 扩展 React.js 组件

javascript - redux如何管理store中的大数据?

javascript - 如何让 column-resizer 在 React 中工作

javascript - 为什么 Array.from(new Set) 在 React jsx 中不起作用

reactjs - 尽管值相等,但单击事件会产生不同的转换延迟

javascript - 带文本输入的自定义对话框 React Native

javascript - 用javascript控制TAB的顺序( react )

javascript - 无法读取未定义 react 的属性 'length'

javascript - React reducer(将对象键添加到对象)