我有以下功能组件
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/