react关于类组件this指向-CSDN博客
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
在 React 中类组件中 this 的指向和普通的 JavaScript 类相同指向当前实例对象。但是在事件处理函数中this 的指向会有所不同。
当我们使用类组件的时候事件处理函数中的 this 默认指向 undefined。为了保证 this 指向类组件实例对象我们需要手动绑定 this或者使用箭头函数。
手动绑定 this:
class MyComponent extends React.Component {
handleClick() {
// do something
}
render() {
return (
<button onClick={this.handleClick.bind(this)}>Click me</button>
);
}
}
使用箭头函数:
class MyComponent extends React.Component {
handleClick = () => {
// do something
}
render() {
return (
<button onClick={this.handleClick}>Click me</button>
);
}
}
在上面的例子中我们使用了箭头函数来定义事件处理函数 handleClick这样就可以保证 this 指向类组件实例对象。
总的来说在 React 中为了保证事件处理函数中的 this 指向类组件实例对象我们需要手动绑定 this 或者使用箭头函数来定义事件处理函数。