第一种:绑定this的情况
<button
style={{ color: this.state.themeColor }}
onClick={this.handleSwitchColor.bind(this, ...)}
>Blue</button>
第二种:ES6 箭头函数情况
<button
style={{ color: this.state.themeColor }}
onClick={() => {
this.handleSwitchColor(...)
}}
>Blue</button>
接收参数方式(需要通过 bind 方法来绑定参数,第一个参数指向 this,第二个参数开始才是事件函数接收到的参数):
<button onClick={this.handleSwitchColor.bind(this, props0, props1, ...}></button>
handleSwitchColor(porps0, props1, ..., event) {
// your code here
}
推荐使用ES6写法,箭头函数除了方便之外还有而一个特征就是将函数的this绑定到其定义时所在的上下文。这个特征也可以帮助我们解决这个问题。个人认为,使用箭头函数使得 JavaScript 更加接近面向对象的编程风格。
<div onClick={() => this.handleClick()}>
You {text} this. Click to toggle.
</div>
this 的总结
this 的本质就是:this跟作用域无关的,只跟执行上下文有关。