React 固定事件监听函数的 this 指向

事件监听函数内部使用 this 会报错,原因是 this 的指向变成了事件触发对应的 DOM 节点,因此需要固定 this,方法有三种:

index.js

import React from 'react'
import ReactDOM from 'react-dom'

class Counter extends React.Component {
  constructor() {
    super()
    this.state = {
      count: 0,
    }
    // 方法1:手动绑定 this
    // this.add = this.add.bind(this)
  }

  add() {
    this.setState({
      count: this.state.count + 1,
    })
  }

  // 方法2 使用实验性语法
  // add = () => {
  //   this.setState({
  //     count: this.state.count + 1,
  //   })
  // }

  render() {
    return <button onClick={this.add}>{this.state.count}</button>

    // 方法3:使用箭头函数包裹
    // return <button onClick={() => this.add()}>{this.state.count}</button>

    // 方法4:在 JSX 中绑定 this
    // return <button onClick={this.add.bind(this)}>{this.state.count}</button>
  }
}

ReactDOM.render(<Counter />, document.getElementById('root'))
原文地址:https://www.cnblogs.com/aisowe/p/15250037.html