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

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

    Your syntax is slightly off, just missing an equals sign after the property name.

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

    This is an experimental feature. You will need to enable experimental features in Babel to get this to compile. Here is a demo with experimental enabled.

    To use experimental features in babel you can install the relevant plugin from here. For this specific feature, you need the transform-class-properties plugin:

    {
      "plugins": [
        "transform-class-properties"
      ]
    }
    

    You can read more about the proposal for Class Fields and Static Properties here


提交回复
热议问题