Javascript React中的受控输入
我是一个新手,最近在React中学习了控制输入。显然,必须在属于组件的事件处理程序中绑定函数。为什么?Javascript React中的受控输入,javascript,reactjs,input,Javascript,Reactjs,Input,我是一个新手,最近在React中学习了控制输入。显然,必须在属于组件的事件处理程序中绑定函数。为什么? class ControlledInput extends React.Component { constructor(props) { super(props); this.state = { input: '' }; // binding in the constructor this.handleChange = this.ha
class ControlledInput extends React.Component {
constructor(props) {
super(props);
this.state = {
input: ''
};
// binding in the constructor
this.handleChange = this.handleChange.bind(this)
}
// what the function does
handleChange(event){
this.setState({
input: event.target.value
})
}
render() {
return (
<div>
<input value = {this.state.input}
{//binding within the component}
<input onChange = {this.handleChange.bind(this)}>
</input>
{//why}
<h4>Controlled Input:</h4>
<p>{this.state.input}</p>
</div>
);
}
};
类ControlledInput扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
输入:“”
};
//构造函数中的绑定
this.handleChange=this.handleChange.bind(this)
}
//函数的作用是什么
手变(活动){
这是我的国家({
输入:event.target.value
})
}
render(){
返回(
.bind(这个)JSX中的
是不必要的。它已经绑定到构造函数中的this
,无需再次执行。执行此操作的原因是,否则this
将不会引用类实例。另一个常见的解决方案是将其设为箭头函数。还有其他几个好的答案可以在d中解释etail.你在哪里学的?这似乎是一个过时的教程^也是一个很好的观点。在React now中很少需要ES6绑定。加上挂钩,功能组件大部分已经取代了基于类的组件。绑定(此)在javascript中,这是因为您在方法中传递您的组件的当前实例。如果您不添加绑定,这将是html元素(此处为输入)的引用。因此,您无法访问您的状态。绑定在类组件中是必需的