react中this指向问题

一.行间定义事件后面使用bind绑定this

run(){
    alert("第一种方法!")
}

<button onClick={this.run.bind(this)}>第一种</button>

//这一种方法使用bind来修改this的指向,需要注意的是bind括号内第一个参数是修改this的,后面可以设置其他参数进行传值。

二.在构造函数内部声明this指向

constructor(props) {
    super(props);
    this.state={
        //定义数据
    }
    this.run = this.run.bind(this);
}
	
run(){
    alert("第二种方法!")
}
 	 
<button onClick={this.run}>第二种</button>

//第二种方法和第一种方法原理一样,只是写的位置不同。

三.声明事件时将事件等于一个箭头函数

run=()=> {
    alert("第三种方法!")
}

<button onClick={this.run}>第三种</button>

//第三种方法是将定义的run方法再等于一个箭头函数,利用箭头函数没有自己的this指针会继承外层的作用域这个特性,来解决this指向问题

四.行间定义事件使用箭头函数

run(){
    alert("第四种方法!")
}

<button onClick={()=>this.run()>第四种</button>
posted @ 2019-06-15 17:39  huihuihero  阅读(541)  评论(0编辑  收藏  举报