假设我有一个名为 Search 的类,它是一个带有提交按钮的简单输入字段。这是它的代码。
class Search extends Component {
constructor(props){
super(props);
this.state = {term: ''};
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
console.log(this);
console.log(e.target.value);
this.setState({term: e.target.value});
}
render() {
return (
<form className='input-group'>
<input className='form-control'
placeholder='City'
onChange={this.handleChange}
value={this.state.value}/>
<span className='input-group-btn'>
<button type='submit' className='btn btn-primary'>Submit</button>
</span>
</form>
)
}
}
因此,我需要将 this
关键字绑定(bind)到类的构造函数中的事件处理程序 handleChange
,以便它具有对 的正确引用this
在 handleChange
事件处理程序中。
但是,如果我把代码改成下面这样
class Search extends Component {
constructor(props){
super(props);
this.state = {term: ''};
//this.handleChange = this.handleChange.bind(this);
Line comment above
}
handleChange(e) {
console.log(this);
console.log(e.target.value);
this.setState({term: e.target.value});
}
render() {
return (
<form className='input-group'>
<input className='form-control'
placeholder='City'
onChange={(e) => this.handleChange(e)}
Line change above
value={this.state.value}/>
<span className='input-group-btn'>
<button type='submit' className='btn btn-primary'>Submit</button>
</span>
</form>
)
}
}
现在,如果我将代码更改为上面的代码,则不再需要这样做,因为我是从回调内部调用 this.handleChange 的。为什么会这样?
最佳答案
原因是您使用了 arrow function当您创建回调时。
您不需要将箭头函数绑定(bind)到 this,因为箭头函数“在词法上绑定(bind)了 this 值”。
如果需要,您可以将事件处理函数更改为箭头函数,这样就不需要绑定(bind)它们了。您可能需要添加 babel 插件 'transform-class-properties'使用箭头函数转换类。
如果你想把handleChange
改成箭头函数,只需改成
handleChange(e) {
...
}
到
handleChange = (e) => {
...
}
关于javascript - 什么时候将此关键字绑定(bind)到 react 中的事件处理程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40656791/