React.Component三种手动绑定this方法

React.Component有三种手动绑定方法:

可以在构造函数中完成绑定
可以在调用时使用method.bind(this)来完成绑定
可以使用arrow function来绑定。

 

拿上例的handleClick函数来说,其绑定可以有:

1、构造函数绑定

    constructor(props) {
       super(props);
       this.handleClick = this.handleClick.bind(this); //构造函数中绑定
  }

2、调用时绑定method.bind(this)

<div onClick={this.handleClick.bind(this)}></div> //使用bind来绑定

3、arrow function箭头函数(调用处)绑定

<div onClick={()=>this.handleClick()}></div> //使用arrow function来绑定

  

 4、arrow function箭头函数(绑定处)调用

  

 

 

 

 

 

 

 

 

.

posted @ 2020-03-01 21:18  剑仙6  阅读(431)  评论(0编辑  收藏  举报
欢迎访问个人网站www.qingchun.在线