React事件绑定的几种方式对比

React事件绑定

因为类的方法默认不会绑定this,所以在调用的时候若是忘记绑定,this的值将会是undefined。
一般若是不是直接调用,应该为方法绑定this。绑定方式有如下几种:javascript

1. 在构造函数中使用bind绑定this

class Button extends React.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 React.Component {
  handleClick(){
    console.log('this is:', this);
  }
  render() {
    return (
      <button onClick={this.handleClick.bind(this)}>
        Click me
      </button>
    );
  }
}

3. 在调用的时候使用箭头函数绑定this

class Button extends React.Component {
  handleClick(){
    console.log('this is:', this);
  }
  render() {
    return (
      <button onClick={()=>this.handleClick()}>
        Click me
      </button>
    );
  }
}

4. 使用属性初始化器语法绑定this(实验性)

class Button extends React.Component {
  handleClick=()=>{
    console.log('this is:', this);
  }
  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}

比较

方式2方式3都是在调用的时候再绑定this。java

  • 优势:写法比较简单,当组件中没有state的时候就不须要添加类构造函数来绑定this
  • 缺点:每一次调用的时候都会生成一个新的方法实例,所以对性能有影响,而且当这个函数做为属性值传入低阶组件的时候,这些组件可能会进行额外的从新渲染,由于每一次都是新的方法实例做为的新的属性传递。

方式1在类构造函数中绑定this,调用的时候不须要再绑定babel

  • 优势:只会生成一个方法实例,而且绑定一次以后若是屡次用到这个方法也不须要再绑定。
  • 缺点:即便不用到state,也须要添加类构造函数来绑定this,代码量多一点。。。

方式4:利用属性初始化语法,将方法初始化为箭头函数,所以在建立函数的时候就绑定了this。
优势:建立方法就绑定this,不须要在类构造函数中绑定,调用的时候不须要再做绑定。结合了方式1方式2方式3的优势
缺点:目前仍然是实验性语法,须要用babel转译函数

总结

方式1是官方推荐的绑定方式,也是性能最好的方式。方式2和方式3会有性能影响而且当方法做为属性传递给子组件的时候会引发重渲问题。方式4目前属于实验性语法,可是是最好的绑定方式,须要结合bable转译性能

相关文章
相关标签/搜索