react学习笔记(二)

在以类继承的方式定义的组件中,为了能方便地调用当前组件的其他成员方法或属性(如: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>

带参数的方法:

在用箭头函数的基础上用bind绑定this和要传的参数

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

原文地址:https://www.cnblogs.com/lzcblog/p/10200810.html