# 12.事件绑定this指向

# 1.箭头函数

  • 利用箭头函数自身不绑定this的特点
  • render() 方法中的this为组件实例, 可以获取到 setState()
class Hello extends React.Component {
  onIncrement() {
    this.setState ({...})
  }
  render() {
    // 箭头函数中的this指向外部环境, 此处为: render() 方法
      return (
      	<button onClick={ () => this.onIncrement() }></button>
      )
  }
}
1
2
3
4
5
6
7
8
9
10
11

# 2.Function.prototype.bind()

  • 利用ES5的bind方法, 将事件处理程序中的this与组件实例绑定到一起
class Hello extends React.Component {
  constructor() {
    super()
    this.onIncrement = this.onIncrement.bind(this)  ⭐⭐
  }
  // ... 省略 onIncremeent
  render() {
    return (
    	<button onClick={this.onIncrement}></button>
    )
  }
}
1
2
3
4
5
6
7
8
9
10
11
12

# 3.class 的实例方法

  • 利用箭头函数形式的class实例方法
  • 注意: 该语法是实验性语法, 但是, 由于babel的存在可以直接使用
class Hello extends React.Component {
  onIncrement = () => {
    this.setState({...})
  }
  render() {
    return (
    	<button onClick={this.onIncrement}></button>
    )
  }               
}
1
2
3
4
5
6
7
8
9
10
上次更新: 2020/10/27 下午11:58:10