React中this的指向问题
此文为个人学习笔记。由于笔者水平十分有限,难免不存在错误或表述不清等问题。如果方便的话,敬请斧正。
背景
问题复现
import React, { Component } from "react";
export default class ClassComponent extends Component {
handler(){
console.log(this); // undefined
}
render(){
return (
<>
<button onClick={this.handler}>BTN</button>
</>
)
}
}
解决方案
-
将事件处理函数修改为箭头函数
-
将事件绑定修改为箭头函数
-
使用
bind改变this指向
方案实现
事件处理函数 => 箭头函数
import React, { Component } from "react";
export default class ClassComponent extends Component {
handler = () => { // 原: handler(){
console.log(this); // ClassComponent
}
render(){
return (
<>
<button onClick={this.handler}>BTN</button>
</>
)
}
}
事件绑定 => 箭头函数
import React, { Component } from "react";
export default class ClassComponent extends Component {
handler(){
console.log(this); // ClassComponent
}
render(){
return (
<>
{/* <button onClick={this.handler}>BTN</button> */}
<button onClick={() => this.handler()}>BTN</button>
</>
)
}
}
bind绑定this
构造器中绑定
import React, { Component } from "react";
export default class ClassComponent extends Component {
// ! ==================
constructor() {
super();
this.handler = this.handler.bind(this);
}
handler(){
console.log(this); // ClassComponent
}
render(){
return (
<>
<button onClick={this.handler}>BTN</button>
</>
)
}
}
事件绑定时绑定
import React, { Component } from "react";
export default class ClassComponent extends Component {
handler(){
console.log(this); // ClassComponent
}
render(){
return (
<>
{/* <button onClick={this.handler}>BTN</button> */}
<button onClick={this.handler.bind(this)}>BTN</button>
</>
)
}
}