react添加方法的两种形式

时间:2023-03-09 16:31:24
react添加方法的两种形式

1.使用bind

<button onClick={this.test.bind(this)}>确定</button>

也可以这么写:

<button onClick={this.test}>确定</button>

在constructor里把bind赋值给方法

 constructor(props){
super(props);
this.state= {
haha:"123"
}
this.test = this.test.bind(this);
}

2.使用箭头函数

 <button onClick={()=>this.test2()}>确定</button>

也可以这么写

 <button  onClick={this.test2}>确定</button>
  test2=()=>{
console.log(222);
console.log(this.state.haha);
}