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

前端 未结 4 1121
隐瞒了意图╮
隐瞒了意图╮ 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 22:57

    You are using arrow function and also binding it in constructor. So you no need to do binding when you use arrow functions

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

    OR you need to bind a function only in constructor when you use normal function like below

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

    Also binding a function directly in render is not recommended. It should always be in constructor

提交回复
热议问题