ES6中bind(this)用法说明

在使用 React 中的 Class extends写法,如果 onClick 绑定一个方法就需要 bind(this),如果使用React.createClass 方法就不需要

解析:

React.createClass 是ES5 的写法默认绑定了 bind 写法
在 ES6 中新增了class,绑定的方法需要绑定 this,如果是箭头函数就不需要绑定 this

示例:

第一种写法:

_handleClick(e){
  console.log(this);
}
render(){
  return (
     <div><h1 onClick={this._handleClick.bind(this)}>点击<h1></div>
 )
}

第二种写法:

constructor(props){
       super(props);
       this._handleClick=this._handleClick.bind(this)
  }
 _handleClick(e){e}{
     console.log(this);
}
render(){
   return(
      <div><h1 onClick={this._handleClick}>点击</h1></div>
  )
}

第三种写法:

  _handleClick=(e)=>{
        //使用箭头函数
       console.log(this);
 }
render(){
   return (
      <div><h1 onClick={this._handleClick}>点击</h1></div>
  )
}
原文地址:https://www.cnblogs.com/YooHoeh/p/9300942.html