Do ES2015 Classes “not autobind”?

前端 未结 5 1068
说谎
说谎 2021-02-09 04:58

I have been using React for a while now, and I have become comfortable with the concept that I must manually bind my component methods to my component instance, as React made th

5条回答
  •  猫巷女王i
    2021-02-09 05:37

    I had similar questions. Methods within your class will be able to reference other methods in the same class, because they are part of the same context (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this).

    This example shows that methods in a class can access properties on this without being bound in the constructor: http://jsbin.com/tapokotahi/1/edit?js,console,output. The renderElements method is not bound, but is accessing this.state.

    The class methods need to be bound (or defined as arrow functions) when they are passed into event handlers, because the execution context changes from that of the class to that of the event handler.

    I agree it seems confusing when we read the React docs and they tell us we need to bind the methods in the constructor, but that is only necessary when passing the methods to React's event handlers such as onClick.

提交回复
热议问题