【问题标题】:What does this.handleClick on the LEFT side of the = sign do?= 符号左侧的 this.handleClick 有什么作用?
【发布时间】:2019-10-02 17:26:56
【问题描述】:

我对@9​​87654324@ 是如何在 ES6 构造函数中使用感到困惑。

首先,我了解以下内容(见下文): - 我们使用this.height = height; 添加一个新的instance variable
- 使用className() {...}添加一个新的实例方法,使用static className() {...}添加一个静态类。
- 在下面的 getter 中使用 this 来引用像 this.calcArea() 这样的实例方法。

class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }
  get area() {   // Getter
    return this.calcArea();
  }
  calcArea() {
    return this.height * this.width;
  }
  static staticMethod() {
    return 'static method has been called.';
  }
}

尽管如此,当我看到下面附上的 React 示例时,ln-7 中的this.handleClick = this.handleClick.bind(this); 让我感到困惑。我理解this.handleClick.bind(this);。我有疑问的部分是this.handleClick,它位于= 标志的LEFT 一侧。 this.handleClick 看起来像是在创建一个名为 handleClick 的 instance variable。在前面的示例中,我以 this.height = height; 的 b/c 方式看待它。

我的问题:我的想法错了吗?或者谁能​​解释=标志的LEFT一侧的this.handleClick做什么?

【问题讨论】:

  • 它用绑定到类上下文的方法替换/覆盖原来的handleClick 方法。就像class A { a = 1; constructor(){ this.a = this.a + 1 } } - 首先定义一个属性,然后用一个新值更新它(可以用原始值创建新值)。
  • 顺便说一句,为了避免在构造函数中使用 binding 样板,您可以使用自动绑定到类上下文的 handleClick = () => {}。我认为它需要babeljs.io/docs/en/babel-plugin-proposal-class-properties 才能正常工作。

标签: javascript reactjs ecmascript-6 ecmascript-5 es6-class


【解决方案1】:

用于将函数绑定到组件实例。看看here。它用于 ES5 函数。如果您使用 ES6 函数,则不需要使用 find。

class Foo extends Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this); // need binding for es5
  }

  handleClick() {
    console.log('Click happened');
  }

  handleClick2 = () => {
    console.log('click happened (es6)');
  }

  render() {
    return (
       <div>
         <button onClick={this.handleClick}>Click Me</button>
         <button onClick={this.handleClick2}>Click Me 2</button>
       </div>
    );
  }
}

注意: this 关键字用于在基本 javascript 类的情况下为对象实例分配值。同样,它被用于反应类。

【讨论】:

  • Naveen,你错过了我的问题。我说我理解绑定部分。我感到困惑的部分是 = 符号左侧的 this.handleClick 的作用。
  • this.handleClick 通过在 this.handleClick 之前添加这个绑定并替换它来覆盖现有的函数属性。
猜你喜欢
  • 2012-08-11
  • 2017-05-12
  • 1970-01-01
  • 2020-10-06
  • 2018-01-12
  • 2012-03-10
  • 1970-01-01
  • 2018-07-08
  • 2016-06-17
相关资源
最近更新 更多