解读React中的事件绑定方式种类以及区别

解读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 = () => {}定义方法,这样性能最佳,使用也相对方便;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章