我是一名新手,正在通过 FreeCodeCamp 学习 React。关于这个挑战,它说:
When you type in the input box, that text is processed by the
handleChange()
method, set as theinput
property in the local state, and rendered as the value in the input box on the page. The component state is the single source of truth regarding the input data.
我写了这个解决方案:
class ControlledInput extends React.Component {
constructor(props) {
super(props);
this.state = {
input: ''
};
// Change code below this line
this.handleChange = this.handleChange.bind(this);
// Change code above this line
}
// Change code below this line
handleChange(event) {
this.setState({
input: event.target.value
})
}
// Change code above this line
render() {
return (
<div>
{ /* Change code below this line */}
<input value={this.state.input} onChange={this.handleChange()} />
{ /* Change code above this line */}
<h4>Controlled Input:</h4>
<p>{this.state.input}</p>
</div>
);
}
};
控制台显示:
“Build error, open your browser console to learn more.”
我哪里做错了?我看不到我的错误..
最佳答案
该问题与您如何将事件处理程序分配给 onChange
有关。
onChange
需要一个回调函数,当输入值更改时将触发该函数。在您的帖子中使用 onChange={this.handleChange()}
时,您实际上将 undefined
分配给 onChange
,因为 handleChange
函数更新组件状态但它不返回任何内容。
将其更改为 onChange={this.handleChange}
即可达到您期望的效果。当输入更改时,将调用 this.handleChange
并将 event
对象作为参数传入。
希望有帮助。
关于javascript - 在 react 中创建受控输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65281728/