1.在事件中绑定this并传参:
<input type="button" value="在事件中绑定this并传参" onClick={this.handleMsg1.bind(this, '?', '?')} />
// 在事件中绑定this并传参
handleMsg1(arg1, arg2) {
console.log(this);
// 此时this是个null
this.setState({
msg: '在事件中绑定this并传参:' + arg1 + arg2
});
}
2.在构造函数中绑定this并传参:
// 修改构造函数中的代码:
this.handleMsg2 = this.handleMsg2.bind(this, '?', '?');
<input type="button" value="在构造函数中绑定this并传参" onClick={this.handleMsg2} />
// 在构造函数中绑定this并传参
handleMsg2(arg1, arg2) {
this.setState({
msg: '在构造函数中绑定this并传参:' + arg1 + arg2
});
}
3.用箭头函数绑定this并传参:
<input type="button" value="用箭头函数绑定this并传参" onClick={() => { this.handleMsg3('?', '?') }} />
// 用箭头函数绑定this并传参
handleMsg3(arg1, arg2) {
this.setState({
msg: '用箭头函数绑定this并传参:' + arg1 + arg2
});
}