React事件綁定幾種方法測試

前提

es6寫法的類方法默認沒有綁定this,不手動綁定this值爲undefined。es6

所以討論如下幾種綁定方式。函數

1、構造函數constructor中用bind綁定

class App extends Component {
  constructor (props) {
    super(props)
    this.state = {
      t: 't'
    }
    // this.bind1 = this.bind1.bind(this) 無參寫法
    this.bind1 = this.bind1.bind(this, this.state.t)
  }

    // 無參寫法 
    // bind1 () {
    //   console.log('bind1', this)
    // }

  bind1 (t, event) {
    console.log('bind1', this, t, event)
  }

  render () {
    return (
      <div>
        <button onClick={this.bind1}>打印1</button>

      </div>
    )
  }
}

2、在調用的時候使用bind綁定this

bind2 (t, event) {
    console.log('bind2', this, t, event)
  }

  render () {
    return (
      <div>
        <button onClick={this.bind2.bind(this, this.state.t)}>打印2</button>
      </div>
    )
  }
// 無參寫法同第一種

3、在調用的時候使用箭頭函數綁定this

bind3 (t, event) {
    console.log('bind3', this, t, event)
  }

  render () {
    return (
      <div>
        // <button onClick={() => this.bind3()}>打印3</button> 無參寫法
        <button onClick={(event) => this.bind3(this.state.t, event)}>打印3</button>
      </div>
    )
  }

4、使用屬性初始化器語法綁定this

bind4 = () =>{
    console.log('bind4', this)
  }

  render () {
    return (
      <div>
        <button onClick={this.bind4}>打印4</button>
        // 帶參須要使用第三種方法包一層箭頭函數
      </div>
    )
  }

附加::方法(不能帶參,stage 0草案中提供了一個便捷的方案——雙冒號語法)

bind5(){
    console.log('bind5', this)
  }

 render() {
   return (
    <div>
       <button onClick={::this.bind5}></button>
    </div>
  )
 }

方法一優缺點

優勢:性能

只會生成一個方法實例;
而且綁定一次以後若是屢次用到這個方法也不須要再綁定。this

缺點:code

即便不用到state,也須要添加類構造函數來綁定this,代碼量多;
添加參數要在構造函數中bind時指定,不在render中。console

方法2、三優缺點

優勢:event

寫法比較簡單,當組件中沒有state的時候就不須要添加類構造函數來綁定this。class

缺點:渲染

每一次調用的時候都會生成一個新的方法實例,所以對性能有影響;
當這個函數做爲屬性值傳入低階組件的時候,這些組件可能會進行額外的從新渲染,由於每一次都是新的方法實例做爲的新的屬性傳遞。構造函數

方法四優缺點

優勢:

建立方法就綁定this,不須要在類構造函數中綁定,調用的時候不須要再做綁定;
結合了方法1、2、三的優勢。

缺點:

帶參就會和方法三相同,這樣代碼量就會比方法三多了。

總結

方法一是官方推薦的綁定方式,也是性能最好的方式。

方法二和方法三會有性能影響,而且當方法做爲屬性傳遞給子組件的時候會引發從新渲染問題。

方法四和附加方法不作評論。

你們根據是否須要傳參和具體狀況選擇適合本身的方法就好。

謝謝閱讀。

相關文章
相關標籤/搜索