react修改状态时,事件绑定,this指向有时候会指向undefined
解决方法
1.class的实例方法
import React from 'react';
import ReactDOM from 'react-dom';
class Hello extends React.Component{
state = {
count:0
}
// 将函数名改成箭头函数,this指向class实例
inCreamCount=()=> {
this.setState({
count:this.state.count+1
})
}
render(){
return (
<div>
<h1>计数器:{this.state.count}</h1>
<button onClick={this.inCreamCount}>+1</button>
</div>
)
}
}
ReactDOM.render(<Hello />,document.getElementById('root'))
2. 绑定事件时,直接改成箭头函数
import React from 'react';
import ReactDOM from 'react-dom';
class Hello extends React.Component{
state = {
count:0
}
inCreamCount() {
this.setState({
count:this.state.count+1
})
}
render(){
return (
<div>
<h1>计数器:{this.state.count}</h1>
{/* 直接改成箭头函数类型 */}
<button onClick={()=>this.inCreamCount()}>+1</button>
</div>
)
}
}
ReactDOM.render(<Hello />,document.getElementById('root'))
3. bind方法
import React from 'react';
import ReactDOM from 'react-dom';
class Hello extends React.Component{
constructor(){
super()
this.state = {
count:0
}
// 利用constructor 添加bind,改变this指向
this.inCreamCount = this.inCreamCount.bind(this)
}
inCreamCount() {
this.setState({
count:this.state.count+1
})
}
render(){
return (
<div>
<h1>计数器:{this.state.count}</h1>
{/* 直接改成箭头函数类型 */}
<button onClick={this.inCreamCount}>+1</button>
</div>
)
}
}
ReactDOM.render(<Hello />,document.getElementById('root'))