[英]Why methods as arrow functions work in react classes but not in normal classes?
We can declare methods of component class as arrow functions, like so: 我们可以将组件类的方法声明为箭头函数,如下所示:
class SomeComponent extends React.Component {
someMethod = () => { // <<----- This does not throw error
// some code
}
}
..that won't throw any error, but below does: ..那不会抛出任何错误,但是下面的错误:
class SomeNormalClass {
someMethod = () => { // <<----- This throws error
// some code
}
}
It says unexpected =
after someMethod
. 在
someMethod
之后,它表示意外的=
。 It works fine if I change my someMethod
back to normal function instead of declaring it as an arrow function as shown below. 如果我将
someMethod
改回正常功能,而不是将其声明为箭头功能,则效果很好,如下所示。 Why? 为什么?
class SomeNormalClass {
function someMethod() { // <<----- This works fine
// some code
}
}
Your someMethod
in first example is a property of the class, not a method. 第一个示例中的
someMethod
是类的属性,而不是方法。 BabelJS support properties in classes, but native js not. BabelJS支持类中的属性,但不支持本机js。 You can see difference here .
您可以在这里看到区别。 You should add some properties in
constructor
for Vanilla JS. 您应该在Vanilla JS的
constructor
添加一些属性。
someMethod = () => {...}
is class field. someMethod = () => {...}
是类字段。 Class fields are stage 3 proposal which isn't natively supported and needs to be transformed by transpiler (Babel); 类别字段是第3阶段的提案 ,其本身不受支持,需要由Transpiler(Babel)进行转换;
someMethod
class field is syntactic sugar for constructor code: someMethod
类字段是构造函数代码的语法糖:
constructor() {
this.someMethod = () => {
// some code
}
}
Both SomeComponent
and SomeNormalClass
are expected to work when used in same conditions. 在相同条件下使用时,
SomeComponent
和SomeNormalClass
都可以正常工作 。 Neither of them will work natively. 他们都不会在本地工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.