How to use arrow functions (public class fields) as class methods?

前端 未结 4 1126
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 22:41

I\'m new to using ES6 classes with React, previously I\'ve been binding my methods to the current object (show in first example), but does ES6 allow me to permanently bind a

4条回答
  •  别那么骄傲
    2020-11-21 23:05

    No, if you want to create bound, instance-specific methods you will have to do that in the constructor. However, you can use arrow functions for that, instead of using .bind on a prototype method:

    class SomeClass extends React.Component {
      constructor() {
        super();
        this.handleInputChange = (val) => {
          console.log('selectionMade: ', val, this);
        };
        …
      }
    }
    

    There is an proposal which might allow you to omit the constructor() and directly put the assignment in the class scope with the same functionality, but I wouldn't recommend to use that as it's highly experimental.

    Alternatively, you can always use .bind, which allows you to declare the method on the prototype and then bind it to the instance in the constructor. This approach has greater flexibility as it allows modifying the method from the outside of your class.

    class SomeClass extends React.Component {
      constructor() {
        super();
        this.handleInputChange = this.handleInputChange.bind(this);
        …
      }
      handleInputChange(val) {
        console.log('selectionMade: ', val, this);
      }
    }
    

提交回复
热议问题