在使用 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>
  )
}

相关文章:

  • 2022-12-23
  • 2021-09-21
  • 2022-01-07
  • 2022-12-23
  • 2022-03-10
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-10-01
  • 2022-12-23
  • 2021-11-17
  • 2021-06-25
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案