方式1
:通过bind方法进行原地绑定,从而改变this指向
注:bind不会调用函数本身,只是改变函数中的this指向,bind会返回一个新的函数,再任何时候调用bind返回的新函数都是bind绑定号的this指向。
方式2
:通过创建箭头函数
方式3
:在constructor中提前对事件进行绑定
方式4
:将事件调用的写法改为箭头函数的形式
<body>
<div id="box"></div>
<script type="text/babel">
class MyCom extends React.Component{
constructor(props){
super(props)
this.state={
texta:"1111",
textb:"2222",
textc:"3333",
textd:"4444"
}
this.fund=this.fund.bind(this)
}
funa(text){
this.setState({
texta:"我是a,我被修改"
})
console.log(text)
}
funb=()=>{
this.setState({
textb:"我是b,我被修改"
})
console.log(this)
}
func(text){
this.setState({
textc:"我是c,我被修改"
})
console.log(text)
}
fund(){
this.setState({
textd:"我是d,我被修改"
})
console.log(this)
}
render(){
return(
<div>
{/*bind(this)的意思是修改了这个单击事件的this指向,让这里的this指向MyCom*/}
<button onClick={this.funa.bind(this,"我是传递过来的实参a")}>使用bind原地绑定的方式修改this指向</button>
<h1>{this.state.texta}</h1>
<button onClick={this.funb}>直接创建箭头函数的方式修改this指向</button>
<h1>{this.state.textb}</h1>
<button onClick={()=>{this.func("我是传递过来的实参c")}}>直接触发回调函数的方式</button>
<h1>{this.state.textc}</h1>
<button onClick={()=>{this.fund()}}>在constructor中提前对事件进行绑定</button>
<h1>{this.state.textd}</h1>
</div>
)
}
}
ReactDOM.render(<MyCom/>,document.getElementById("box"))
</script>
</body>