第一种方式:(推荐使用第一种)
// class类的实例方法 改变this指向
class Hello extends React.Component{
state={
count:0
}
onincrement=()=>{
this.setState({
count:this.state.count+1
})
}
render(){
return (
<div>
<h1>计数器:{this.state.count}</h1>
<button onClick={ this.onincrement}>+1</button>
</div>
)
}
}
第二种方式:
// 事件调用的时候用箭头函数
class Hello extends React.Component{
state={
count:0
}
onincrement(){
this.setState({
count:this.state.count+1
})
}
render(){
return (
<div>
<h1>计数器:{this.state.count}</h1>
<button onClick={ ()=>this.onincrement()}>+1</button>
</div>
)
}
}
第三种方式:
// 用bind的改变this
class Hello extends React.Component{
state={
count:0
}
constructor(){
super() //内置函数
this.onincrement = this.onincrement.bind(this)
}
}
onincrement(){
this.setState({
count:this.state.count+1
})
render(){
return (
<div>
<h1>计数器:{this.state.count}</h1>
<button onClick={ this.onincrement}>+1</button>
</div>
)
}
}