React事件綁定的方式


一、是什么

react應用中,事件名都是用小駝峰格式進行書寫,例如onclick要改寫成onClick

最簡單的事件綁定如下:

class ShowAlert extends React.Component {
  showAlert() {
    console.log("Hi");
  }

  render() {
    return <button onClick={this.showAlert}>show</button>;
  }
}

從上面可以看到,事件綁定的方法需要使用{}包住

上述的代碼看似沒有問題,但是當將處理函數輸出代碼換成console.log(this)的時候,點擊按鈕,則會發現控制台輸出undefined

二、如何綁定

為了解決上面正確輸出this的問題,常見的綁定方式有如下:

  • render方法中使用bind
  • render方法中使用箭頭函數
  • constructor中bind
  • 定義階段使用箭頭函數綁定

render方法中使用bind

如果使用一個類組件,在其中給某個組件/元素一個onClick屬性,它現在並會自定綁定其this到當前組件,解決這個問題的方法是在事件函數后使用.bind(this)this綁定到當前組件中

class App extends React.Component {
  handleClick() {
    console.log('this > ', this);
  }
  render() {
    return (
      <div onClick={this.handleClick.bind(this)}>test</div>
    )
  }
}

這種方式在組件每次render渲染的時候,都會重新進行bind的操作,影響性能

render方法中使用箭頭函數

通過ES6的上下文來將this的指向綁定給當前組件,同樣在每一次render的時候都會生成新的方法,影響性能

class App extends React.Component {
  handleClick() {
    console.log('this > ', this);
  }
  render() {
    return (
      <div onClick={e => this.handleClick(e)}>test</div>
    )
  }
}

constructor中bind

constructor中預先bind當前組件,可以避免在render操作中重復綁定

class App extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick() {
    console.log('this > ', this);
  }
  render() {
    return (
      <div onClick={this.handleClick}>test</div>
    )
  }
}

定義階段使用箭頭函數綁定

跟上述方式三一樣,能夠避免在render操作中重復綁定,實現也非常的簡單,如下:

class App extends React.Component {
  constructor(props) {
    super(props);
  }
  handleClick = () => {
    console.log('this > ', this);
  }
  render() {
    return (
      <div onClick={this.handleClick}>test</div>
    )
  }
}

三、區別

上述四種方法的方式,區別主要如下:

  • 編寫方面:方式一、方式二寫法簡單,方式三的編寫過於冗雜
  • 性能方面:方式一和方式二在每次組件render的時候都會生成新的方法實例,性能問題欠缺。若該函數作為屬性值傳給子組件的時候,都會導致額外的渲染。而方式三、方式四只會生成一個方法實例

綜合上述,方式四是最優的事件綁定方式

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM