this的绑定问题
在事件执行后,我们可能需要获取当前类的对象中相关的属性,这个时候需要用到this,如果我们这里直接打印this,会发现它是一个undefined,那么为什么是undefined呢?
原因是btnClick函数并不是我们主动调用的,而是React内部帮我们自动调用了btnClick函数,而当内部调用时,并不知道要如何绑定正确的this。
如何解决this的问题呢?
方案一:使用bind给btnClick显示绑定this。
方案二:定义函数时, 使用箭头函数。
方案三:在事件监听时直接传入一个箭头函数,然后在箭头函数中直接调用所需要执行的函数即可(推荐)
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
message: "你好啊",
counter: 100
}
//显示绑定this
this.btnClick = this.btnClick.bind(this);
}
render() {
return (
<div>
{/* 1.方案一: bind绑定this(显示绑定) */}
<button onClick={this.btnClick}>按钮1</button>
{/* 2.方案二: 定义函数时, 使用箭头函数 */}
<button onClick={this.increment}>+1</button>
{/* 2.方案三(推荐): 直接传入一个箭头函数, 然后在箭头函数中调用所需要执行的函数*/}
<button onClick={() => { this.decrement("why") }}>-1</button>
</div>
)
}
btnClick() {
console.log(this.state.message);
}
increment = () => {
console.log(this.state.counter);
}
decrement(name) {
console.log(this.state.counter, name);
}
}
其实这也是使用类组件的一大不方便之处,因此在hooks出现之后,便很少再去使用类组件了,因为不用再考虑this的指向问题了。