class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
weather: '热天'
}
}
render() {
return (
<button onClick={this.upDateWeather}>点击</button>
)
}
upDateWeather() {
console.log(this)
}
}
像这种使用方式直接报undefined,获取this.setSate:Uncaught TypeError: Cannot read property 'setState' of undefined

这里的this获取到的是upDateWeather的上下文环境,而不是对象的this,原因:this.upDateWeather作为onClick的回调,不是通过对象的实例调用的原型链的,属于直接拿出来调用,直接调用获取的this是window,但是默认在方法的内部开启了严格模式(局部严格模式),导致获取的this是没有定义,当然找不到setState。需要使用以下方法:
1、使用bind在onClick中绑定
<button onClick={this.upDateWeather.bind(this)}>点击</button>
bind关键字将实例对象的上下文传递给upDateWeather方法,这样执行时候的this就是对象的this。注意调用的是原型链中的upDateWeather方法,注意这里还不是对象的upDateWeather,而是原型链的。

注意这里upDateWeather没有括号,有了括号相当于将upDateWeather的返回值赋值给onClick,还没有点就执行了,再次点击无效。
2、使用bind在constructor中绑定指向
constructor(props) {
super(props);
this.state = {
weather: '热天'
}
this.upDateWeather = this.upDateWeather.bind(this)
}
render() {
return (
<button onClick={this.upDateWeather}>点击</button>
)
}
在实例中定义一个upDateWeather,通过bind生成新的函数赋值给对象,实际上对象中存在两个,一个是对象的upDateWeather,另一个是原型链的upDateWeather,首先找到的是对象的upDateWeather,进而执行。

3、使用匿名
<button onClick={() => this.upDateWeather()}>点击</button>
注意这里upDateWeather有括号,onClick是函数赋值,执行函数的,箭头函数的this是当前实例的this,所以能直接获取到。

4、使用箭头函数
render() {
return (
<button onClick={this.upDateWeather}>点击</button>
)
}
upDateWeather = () => {
console.log(this)
}

相当于对象自己的一个方法,这时候由于箭头函数没有this,this直的是外面对象的,这时候就不是原型对象的了,开发中提倡这样,注意不能将箭头函数改为function,否也报错。
本文探讨了在React组件中,`this`指针在事件处理函数中为何会变成`undefined`,并详细解释了四种解决方案:1) 使用`bind(this)`在`onClick`中绑定;2) 在`constructor`中预先绑定`this`;3) 使用箭头函数定义事件处理方法;4) 直接在箭头函数中调用事件处理方法。理解这些方法有助于避免在React开发中遇到的常见错误。
609

被折叠的 条评论
为什么被折叠?



