Catalog
  1. 1. bind(this)的原因
  2. 2. 其他绑定this的方法
  3. 3. 推荐阅读
Class类型的组件内部函数为什么需要bind(this)?

bind(this)的原因

  • JavaScript中,class内定义的方法默认情况下不会绑定this,所以我们要使用bind()手动绑定this,使this时刻指向组件本身

其他绑定this的方法

  1. 定义时绑定

    1
    2
    3
    4
    5
    // 此语法确保 `handleClick` 内的 `this` 已被绑定。
    // 注意: 这是 *实验性* 语法。
    handleClick = () => {
    console.log('this is:', this);
    }
  2. 调用时绑定

    1
    2
    3
    4
    5
    6
    7
    8
    render() {
    // 此语法确保 `handleClick` 内的 `this` 已被绑定。
    return (
    <button onClick={(e) => this.handleClick(e)}>
    Click me
    </button>
    );
    }

推荐阅读

Author: Erealm
Link: http://erealmsoft.github.io/2019/09/18/react/react-bind-this/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.

Comment