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>
  )
}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM