这是我的第一篇掘金博客,开启掘金写作之路。
在这里记录一下如何使用箭头函数来解决事件绑定中的this指向问题,若有错误,还请批评指正。 首先先从最初使用箭头函数的情况说起。
初始使用箭头函数的方法:
render() {
return (
<div>
<h1>计数器:{ this.state.count}</h1>
<button onClick={() => {
this.setState({ //这里是在render方法内部,this是组件实例。 所以箭头函数的this也是组件实例。
count: this.state.count + 1
})
}}>+1</button>
</div>
)
}
最初:this指向没问题。但是JSX中掺杂了过多js代码,需要改进。
正确原因:箭头函数没有自己的this,箭头函数的this指向外部函数的作用域,即render方法,即组件实例。组件实例可以调用setState方法。
上面的就是最初箭头函数的用法,下面列出它的优化做法。
用箭头函数解决的方法一:
onIncrement() {
console.log('事件处理程序中的this:', this) //这里的this是组件实例。
this.setState({
count: this.state.count + 1
})
}
render() {
return (
<div>
<h1>计数器:{ this.state.count}</h1>
<button onClick={() => this.onIncrement()}>+1</button>//正确做法。
<button onClick={this.onIncrement}>+1</button> //错误做法。
</div>
)
}
}
错误做法中:console.log中的this是undefined,无法调用setState方法。
正确方法中:箭头函数体中用this调用onIncrement函数。
onIncrement函数中:谁调用该函数,该函数中的this就指向谁。是this调用,this是组件实例,即组件实例调用。
该函数中的this就指向了组件实例,组件实例调用setState方法。
用箭头函数解决的方法二:
onIncrement = () => {
console.log('事件处理程序中的this:', this)
this.setState({
count: this.state.count + 1
})
}
render() {
return (
<div>
<h1>计数器:{ this.state.count}</h1>
<button onClick={this.onIncrement}>+1</button>//正确做法。
</div>
)
}
}
组件实例的属性名是onIncrement,属性值是箭头函数。取出组件实例的属性值就是箭头函数。
以上就是我对于箭头函数从浅到深的理解记录,稍作总结。