React事件綁定this的幾種方法

React事件處理函數(shù)綁定this的集中方法

Follow me on GitHub

目前React有三種方法可以創(chuàng)建組件,其中使用React.createClass()函數(shù)創(chuàng)建的組件,this會自動
綁定到組件的每個(gè)方法中;而使用Class Component或者Functional Component時(shí),需要手動綁定this.

1. 在構(gòu)造函數(shù)中綁定

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    // This binding is necessary to make `this` work in the callback
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      isToggleOn: !prevState.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

ReactDOM.render(
  <Toggle />,
  document.getElementById('root')
);

2.使用class properties進(jìn)行綁定

class properties目前處于state-2草案階段,babel已經(jīng)支持

class LoggingButton extends React.Component {
  // This syntax ensures `this` is bound within handleClick.
  // Warning: this is *experimental* syntax.
  handleClick = () => {
    console.log('this is:', this);
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        Click me
      </button>
    );
  }
}

3. 使用箭頭函數(shù)

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // This syntax ensures `this` is bound within handleClick
    return (
      <button onClick={(e) => this.handleClick(e)}>
        Click me
      </button>
    );
  }
}

這種方式有一個(gè)潛在的性能問題,就是每次組件渲染時(shí),onClick的回調(diào)函數(shù)都是不同的匿名函數(shù),如果這個(gè)組件把回調(diào)函數(shù)通過props傳遞到其子組件,那么由于每次組件的渲染時(shí),由于傳遞的props中回調(diào)函數(shù)的變化,就會導(dǎo)致子組件的額外渲染(是不同的回調(diào)函數(shù),但實(shí)際上處理邏輯完全相同)。

4. 使用bind()

class LoggingButton extends React.Component {
  handleClick() {
    console.log('this is:', this);
  }

  render() {
    // This syntax ensures `this` is bound within handleClick
    return (
      <button onClick={this.handleClick.bind(this)}>
        Click me
      </button>
    );
  }
}

bind跟使用箭頭函數(shù)一樣,實(shí)際上每次組件渲染時(shí)都生成了新的回調(diào)函數(shù)。


建議使用構(gòu)造函數(shù)中綁定或者使用class properties特性綁定,但bind箭頭函數(shù)在特殊場景下需要使用,即需要傳遞額外參數(shù)的情況。

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 本筆記基于React官方文檔,當(dāng)前React版本號為15.4.0。 1. 安裝 1.1 嘗試 開始之前可以先去co...
    Awey閱讀 7,932評論 14 128
  • 深入JSX date:20170412筆記原文其實(shí)JSX是React.createElement(componen...
    gaoer1938閱讀 8,183評論 2 35
  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,578評論 19 139
  • 自己最近的項(xiàng)目是基于react的,于是讀了一遍react的文檔,做了一些記錄(除了REFERENCE部分還沒開始讀...
    潘逸飛閱讀 3,741評論 1 10
  • 以下內(nèi)容是我在學(xué)習(xí)和研究React時(shí),對React的特性、重點(diǎn)和注意事項(xiàng)的提取、精練和總結(jié),可以做為React特性...
    科研者閱讀 8,409評論 2 21

友情鏈接更多精彩內(nèi)容