解读React中的事件绑定方式种类以及区别
本章节主要介绍React
的事件绑定方式,由于类的方法默认不会绑定this,因此在调用的时候如果忘记绑定,this
的值将会是undefined
。
通常如果不是直接调用,应该为方法绑定this。所以我们来解读下有多少种方式可以绑定this
,以及它们的区别有哪些?
答:4种,哪4种呢,大家继续往下看:
4
种方式绑定this
1. 在构造函数中使用bind绑定this
class Button extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
console.log('this is:', this);
}
render() {
return (
<button onClick={this.handleClick}>
Click me
</button>
);
}
}
2. 在调用的时候使用bind绑定this
class Button extends Component {
handleClick(){
console.log('this is:', this);
}
render() {
return (
<button onClick={this.handleClick.bind(this)}>
Click me
</button>
);
}
}
3. 在调用的时候使用箭头函数绑定this
class Button extends Component {
handleClick(){
console.log('this is:', this);
}
render() {
return (
<button onClick={()=>this.handleClick()}>
Click me
</button>
);
}
}
4. 在声明方法的时候使用箭头方法绑定this
class Button extends Component {
handleClick=()=>{
console.log('this is:', this);
}
render() {
return (
<button onClick={this.handleClick}>
Click me
</button>
);
}
}
几种方式的区别
- 在调用的使用绑定
this
,我们可以采用bind(this)
及()=>(this.xxx())
绑定的方式;优点:简单;缺点:每次渲染生成,降低性能; - 在初始化的绑定
this
,我们可以在constructor
中及使用xxx = () => {}
这样来绑定; 优点:只生成一次;缺点:代码多点; - 总结:建议使用
xxx = () => {}
定义方法,这样性能最佳,使用也相对方便;