![](/img/trans.png)
[英]May I know why we need to add a const/var/let sometimes before arrow function in React?
[英]Cannot store arrow function in let/var in React Component
我在扩展React.Component定义的react中有一个组件。 其中的内部以及render方法是:
constructor(props, context) {
super(props, context);
this.state = {
open: false,
};
}
handleClose = () => { //this works
this.setState({open: false});
};
handleOpen = () => { //this works
this.setState({open: true});
};
let empty = () => {}; // does not work, error Parsing error: Unexpected token
如果我在let或const的任何箭头函数之前加上前缀,似乎会出现意外的令牌错误。 我在这里想念什么吗?
谢谢
阅读有关类的babel文档 。 使用let
或const
不是类定义的ES6可能前缀的一部分
ECMA 2015规范似乎只允许在类定义的主体中使用methods
和static methods
。
因此,在这种情况下,不允许使用赋值语句,因此来自babel的Unexpected token
错误。
您正在尝试使用实验性的ES7功能,并且可能仅启用了ES6(也不能在类中添加let或const前缀)。 如果您使用的是babel6,则切换到正确的插件应该很简单。 从基本上相同的问题看这个答案: 如何在类方法中使用ES6箭头?
您似乎正在使用类属性声明建议 。 建议的语法为:
class ClassWithoutInits { myProp; } class ClassWithInits { myProp = 42; }
如您所见,没有let
或const
或var
。 let empty = () => {};
无效,因为它是无效的语法,就像错误消息告诉您一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.