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