react事件綁定this的4種寫法

react事件綁定this的幾種寫法

正常我們不綁定this,this是null

import React, { Component } from 'react'

export default class App extends Component {
  constructor() {
    super()
    this.state = { }
  }
  clickHandler() {
    console.log("this",this);
  }
  render() {
    return (
      <div>
        <h1>我是App頁面</h1>
        <button onClick={ this.clickHandler }>點擊按鈕</button>
      </div>
    )
  }
}
image.png

1: this.clickHandler.bind(this)

import React, { Component } from 'react'
export default class App extends Component {
  constructor() {
    super()
    this.state = {}
  }
  clickHandler() {
    console.log("this",this);
  }
  render() {
    return (
      <div>
        <h1>我是App頁面</h1>
        <button onClick={ this.clickHandler.bind(this) }>點擊按鈕</button>
      </div>
    )
  }
}

2: this.clickHandler = this.clickHandler.bind(this)

import React, { Component } from 'react'
export default class App extends Component {
  constructor() {
    super()
    this.state = {}
    this.clickHandler = this.clickHandler.bind(this)
  }
  clickHandler() {
    console.log("this",this);
  }
  render() {
    return (
      <div>
        <h1>我是App頁面</h1>
        <button onClick={ this.clickHandler }>點擊按鈕</button>
      </div>
    )
  }
}

3: () => this.clickHandler()

import React, { Component } from 'react'
export default class App extends Component {
  constructor() {
    super()
    this.state = {}
  }
  clickHandler() {
    console.log("this",this);
  }
  render() {
    return (
      <div>
        <h1>我是App頁面</h1>
        <button onClick={ () => this.clickHandler() }>點擊按鈕</button>
      </div>
    )
  }
}

4: clickHandler = () => { console.log("this",this); } (工作中推薦這種寫法)

import React, { Component } from 'react'
export default class App extends Component {
  constructor() {
    super()
    this.state = {}
  }
  clickHandler = () => { console.log("this",this); } // 推薦寫法
  render() {
    return (
      <div>
        <h1>我是App頁面</h1>
        <button onClick={ this.clickHandler }>點擊按鈕</button>
      </div>
    )
  }
}

4中綁定this展示效果

image.png
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容