1. this指向

在以类继承的方式定义的组件中,为了能方便地调用当前组件的其他成员方法或属性(如:this.state),通常需要将事件处理函数运行时的 this 指向当前组件实例。

绑定事件处理函数this的几种方法:

第一种方法:

   run(){

 

         alert(this.state.name)

   }

   <button onClick={this.run.bind(this)}>按钮</button>

 

第二种方法:

构造函数中改变

 

this.run = this.run.bind(this);

 

 

  run(){

 

         alert(this.state.name)

   }

  <button onClick={this.run>按钮</button>

第三种方法:

 

 

 run=()=> {

     alert(this.state.name)

   }

 

<button onClick={this.run>按钮</button>

 

相关文章:

  • 2021-12-01
  • 2021-07-16
  • 2021-10-10
  • 2022-12-23
  • 2021-12-05
  • 2021-07-16
猜你喜欢
  • 2021-11-12
  • 2021-03-31
  • 2022-01-22
  • 2022-12-23
  • 2022-12-23
  • 2021-04-10
相关资源
相似解决方案