React类组件中箭头函数类方法为何无需手动绑定this即可调用
原因解答
这里的{this.increment}不需要手动做.bind(this)绑定就能正常运行,核心原因是你定义increment用的是类公共字段+箭头函数的写法,和普通类方法的this逻辑完全不一样:
- 普通类方法的
this是动态绑定的:要是你把increment写成普通类方法increment() { this.setState(...) },这个方法是挂在类原型上的。当你把它直接传给onClick当回调时,函数会被抽离出来单独执行,和组件实例脱钩,内部的this就不会指向当前组件,拿不到setState、state这些实例属性,这时候才需要在构造函数里用.bind(this)、或者渲染的时候套一层箭头函数来固定this指向。 - 类字段箭头函数的
this是静态继承来的:你写的increment = () => { ... }是组件实例自己的属性,不是原型方法。箭头函数本身根本没有自己的this,它的this直接拿的是定义位置所在上下文的this——类字段初始化的时候,上下文的this就是当前组件实例,而且这个指向一旦确定就不会变,不管你把这个函数传到哪里当回调,内部的this永远指向当前组件实例,自然不需要额外做绑定。
对应示例代码:
export default class App extends Component { constructor(props) { super(props) this.state = { count: 0 } } increment = () => { this.setState({ count: this.state.count + 2 }) } render() { return ( <> <div id='1'>{this.state.count}</div> <button onClick={this.increment}>Increment </button> </> ) } }
内容的提问来源于stack exchange,提问作者Harshad Pawar
相关产品推荐
相关产品推荐

