this指向为undefined问题代码重现
代码中TestComponent类组件中有名为handler的方法,在按钮添加点击事件调用handler时,找不到handler方法的this。
class TestComponent extends React.Component {
handler() {
console.log(this)
}
render () {
return (
<div>
<button onClick={this.handler}>点击调用handler方法</button>
</div>
)
}
}
此时控制台输出为undefined;找不到this,不能对组件中的属性进行操作;
问题原因
React文档
- 在JavaScript中,class中的方法默认不会绑定this。
- 这并不是React特有的行为;这其实与JavaScript函数工作原理有关。通常情况下,如果你没有在方法后面添加(),例如onClick={this.handler},你应该该为handler这个方法绑定this。
补充
我看别人是这么解释的:
- 所有在类中定义的方法都默认开启局部严格模式,所以在Class组件当中:
- 所有指向window对象的this都指向undefined
- 所有内联的的事件处理处理函数当中的this都指向undefined
解决办法
方法一:通过construcor做修正
在class组件中通过constructor结合super和bind绑定this
constructor () {
super()
//使用bind强行修正this指向
//相当于在类组件初始化的阶段 就可以把回调函数的this修正到永远指向当前组件实例对象
this.handler = this.handler.bind(this)
}
此时点击调用handler事件,this可以被打印出来(当前组件的实例对象)。
方法二:通过在onClick中使用箭头函数
this.handler改写为 () =>this.handler()。通过箭头函数的写法,直接沿用父函数中的this指向,此处就是render的this指向。
render () {
return (
<div>
<button onClick={() => this.handler()}>点击调用handler方法</button>
</div>
)
}
方法三:修改handler写法,此方法为最优写法
将handler写成箭头函数的形式,onClick中直接写this.handler即可。
handler = () => {
console.log(this)
}