在react
组件中,特别要小心this
的使用。比如,在Counter
那个示例中,我们使用以下方式声明increment
和decrement
方法:
import React, { Component } from "react"
import ReactDOM from "react-dom"
class Counter extends Component {
state = {
count: 0,
}
increment() {
this.setState({
count: this.state.count + 1
})
}
decrement() {
this.setState({
count: this.state.count - 1
})
}
render() {
return (
<div>
<h1>一共点击了{this.state.count}次</h1>
<input type="button" value="+" onClick={this.increment.bind(this)} />
<input type="button" value="-" onClick={this.decrement.bind(this)} />
</div>
)
}
}
ReactDOM.render(<Counter />, document.querySelector("#root"))
这时,点击按钮之后,控制台抛出以下异常:
导致这个异常的原因,实际就是this
的指向问题
解决方案是将this
的指向固定下来,最简单的方式就是通过箭头函数来声明方法。
increment = () => {
this.setState({
count: this.state.count + 1
})
}
decrement = () => {
this.setState({
count: this.state.count - 1
})
}
使用箭头函数的方式来声明方法,函数中的this
指向函数声明时所在的作用域。因此,increment
和decrement
函数中的this
就会一直指向当前Counter
产生的实例,即使是传递给input
元素来调用。
除了使用箭头函数固化this
以外,还可以使用bind
方法,在声明函数时,依然使用普通函数:
increment() {
this.setState({
count: this.state.count + 1
})
}
decrement() {
this.setState({
count: this.state.count - 1
})
}
绑定函数的时候,我们需要可以使用bind
方法,将当前的作用域绑定到函数上:
<input type="button" value="+" onClick={this.increment.bind(this)} />
<input type="button" value="-" onClick={this.decrement.bind(this)} />
这两种方法都可以用来固化this
。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。