react 类组件事件绑定 this
指向问题
1. 普通绑定 - 触发单击事件
class App extends React.Component{
// 事件函数
fn1(){
console.log('fn1')
console.log(this) // undefined
}
render(){
<button onClick={ this.fn1 }>按钮1</button>
}
}
-
单击
按钮1
,控制台打印结果如下:
this
指向 undefined
?
-
利用
JS
类实验得到以下结果:// 定义 Star 类 class Star { thisDirection() { console.log(this); } } var star = new Star(); star.thisDirection(); // 实例调用 const x = star.thisDirection; // 保存方法 x(); // 直接调用
- 控制台打印结果如下:
-
类中所有的方法,在局部默认开启了严格模式,它不敢指向
window
所以指向了undefined
。
结论:在 React
事件普通绑定中,由于直接调用了类中的方法,所以 this
指向 undefined
为了解决 this
指向问题,React
还提供了其他绑定方式:
2. bind
绑定:
-
通过bind改变点击事件内的this指向外部组件内this (使用较多)
class App extends React.Component{ // 事件函数 fn2(){ console.log('fn2'); console.log(this); // Class } render(){ <button onClick={ this.fn2.bind(this) }>按钮2</button> } }
-
通过在构造函数constructor内使用bind对函数内的this重定向
class App extends React.Component{ constructor(){ super() // ES6 类继承类, constructor() 里面用 this 必须调用 super() 函数 // this 指向当前类组件 // 调用公用的 属性 和 方法 必须加 this this.fn3 = this.fn3.bind(this) } // 事件函数 fn3(){ console.log('fn3'); console.log(this); // Class } render(){ <button onClick={ this.fn3 }>按钮3</button> } }
3. 箭头函数绑定:
-
通过使用箭头函数来指向外部组件内this (使用较多)
class App extends React.Component{ // 事件函数 fn4(){ console.log('fn4'); console.log(this); // Class } render(){ <button onClick={ () => this.fn4() }>按钮4</button> } }
-
将事件函数写成箭头函数来指向外部组件内this (使用较多)
class App extends React.Component{ fn5 = () => { console.log('fn5'); console.log(this); } render(){ <button onClick={ this.fn5 }>按钮5</button> } }