Unable to use Arrow functions inside react component class [duplicate]

梦想与她 提交于 2019-11-26 22:52:28

It's not the arrow function that's causing a problem here. Class properties are not part of the ES6 specification.

handleUpdateInput = (value) => {
  // ...
};

If you want to be able to transform this code, you'll need to add the class properties babel plugin.

Alternatively, this transform is provided as part of Babel's stage 2 preset.

Using an arrow function with a class property ensures that the method is always invoked with the component as the value for this, meaning that the manual rebinding here is redundant.

this.handleUpdateInput = this.handleUpdateInput.bind (this);

It is not a problem of arrow function but using it inside class declaration, this code will work in constructor body or any other function body but not in class declaration.

Code should look just like that:

handleUpdateInput(value){
  this.setState({
    dataSource: [
      value,
      value + value,
      value + value + value,
    ],
  });
};

Using arrow function can be done inside any class method, but not inside class declaration. For example using arrow function in constructor:

constructor(props,context){
   super(props,context);

   this.someFunc = ()=>{
     //here function code
   };
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!