react事件绑定this的原因

1.首先是js本身特性决定的

this永远指向最后调用它的那个对象

var name='windowName';
function a(){ 
  var name ='objName';   
  console.log(this.name)
}
a();//windowName ; this永远指向最后调用它的对象。window.a()




var name='windowName';
var obj={
  name:'objName',
  fun1:function(){
     console.log(this.name)
  }  
}
obj.fun1();//objName : this永远指向最后调用它的对象

2.在react事件中绑定this,来使事件的this指向当前组件,避免this的丢失

var name='windowName';
var obj={
  name:'objName',
  fun:function(){
   console.log(this.name)
  }
}
var fn = obj.fun;
fn();//windowName  这里只是将obj.fun赋值给一个变量。但是没有调用。this永远指向最后调用它的对象。这里还是通过window.fn();
//bind的复习
//bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
var a ={
        name : "Cherry",
        fn : function (a,b) {
            console.log( a + b)
        }
    }

    var b = a.fn;
    b.bind(a,1,2)()//将b的this指向a,然后在调用bind()方法创建的函数



//react中
<Button   onClick={this.handleClick}>绑定this</Button>
//这个时候onClick就当于一个变量,它指向window。你直接调用handleClick去做一些操作的时候,比如this.setState({});这个时候this指向就会报错。所以我们需要给react事件绑定this来方式this的丢失
//第一种是使用bind
<Button   onClick={this.handleClick.bind(this)}>绑定this</Button>
//通过bind()来把this指向的当前的组件
handleClick(){}
//使用箭头函数
<Button   onClick={this.handleClick}>绑定this</Button>
handleClick=()=>{};//ES6 的箭头函数是可以避免 ES5 中使用 this 的坑的。箭头函数的 this 始终指向函数定义时的 this,而非执行时。,箭头函数需要记着这句话:“箭头函数中没有 this 绑定,必须通过查找作用域链来决定其值,如果箭头函数被非箭头函数包含,则 this 绑定的是最近一层非箭头函数的 this,否则,this 为 undefined”。

参考文献:https://juejin.im/post/59bfe84351882531b730bac2#heading-2

https://my.oschina.net/shuaihong/blog/2990055

猜你喜欢

转载自www.cnblogs.com/lppswkf/p/13374525.html
今日推荐