React-事件绑定

一、class方式定义组件事件绑定的几种方法

  • 由于类的方法默认不会绑定this,因此在调用时候如果忘记绑定,this的值将会是undefined。通常如果不是直接调用,应该为方法绑定this,绑定方式有以下几种:

  (一)在构造函数中使用bind绑定this

    

 1 class Button extends React.Component {
 2 constructor(props) {
 3     super(props);
 4     this.handleClick = this.handleClick.bind(this);
 5   }
 6   handleClick(){
 7     console.log('this is:', this);
 8   }
 9   render() {
10     return (
11       <button onClick={this.handleClick}>
12         Click me
13       </button>
14     );
15   }
16 }

  (二)在调用的时候使用bind去绑定this

    

 1 class Button extends React.Component {
 2   handleClick(){
 3     console.log('this is:', this);
 4   }
 5   render() {
 6     return (
 7       <button onClick={this.handleClick.bind(this)}>
 8         Click me
 9       </button>
10     );
11   }
12 }

  (三)调用的时候使用箭头函数绑定this

    

 1 class Button extends React.Component {
 2   handleClick(){
 3     console.log('this is:', this);
 4   }
 5   render() {
 6     return (
 7       <button onClick={()=>this.handleClick()}>
 8         Click me
 9       </button>
10     );
11   }
12 }

  (四)使用属性初始化语法直接绑定

    

 1 class Button extends React.Component {
 2   handleClick=()=>{
 3     console.log('this is:', this);
 4   }
 5   render() {
 6     return (
 7       <button onClick={this.handleClick}>
 8         Click me
 9       </button>
10     );
11   }
12 }

二、比较上述几个方式的优劣

  • (二)和 (三) 方法都是调用的时候再绑定 this
    • 优点: 写法简单,组件中没有 state 的时候不需要添加构造函数来绑定 this
    • 缺点: 每一次调用的时候都会生成一个新的方法实例,因此对性能有影响,并且当这个函数作为属性值传入低阶组件的时候,这些组件可能会进行额外的重新渲染,因为每一次都是新的方法实例作为的新的属性传递。
  • (一)方法在构造函数中绑定了 this,调用的时候不需要二次绑定
    • 优点:只会生成一个方法实例,并且绑定一次之后如果多次用到这个方法也不需要绑定了。
    • 缺点:即使不适用 state 的时候也需要在构造函数中绑定 this,代码量多。
  • (四)方法 利用属性初始化语法,将方法初始化为箭头函数,因此在创建函数的时候就绑定了this。
    • 优点:创建方法就绑定this,不需要在类构造函数中绑定,调用的时候不需要再作绑定。结合了方式1、方式2、方式3的优点
    • 缺点:以前有需要 babel 转移的需求,现在随着性能越来越好,也会考虑这一点消耗的问。

三、事件绑定方法总结

  方式一是官方推荐的绑定方式,也是性能最好的方式。方式二和凡是三会有性能影响并且当方法作为属性传递给子组件的时候会引起重渲问题。方式四是性能比较好的,现在 babel 已经很成熟了,推荐大家使用

猜你喜欢

转载自www.cnblogs.com/liufuyuan/p/10837402.html