简体   繁体   English

为什么作为箭头函数的方法在React类中起作用而在普通类中不起作用?

[英]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. 在相同条件下使用时, SomeComponentSomeNormalClass都可以正常工作 Neither of them will work natively. 他们都不会在本地工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JS 类与普通对象中的箭头函数有何不同 - How arrow functions differ in JS Classes vs Normal objects 具有静态箭头功能的类 - Classes with static arrow functions 在课程中使用Ecmascript 6箭头函数作为方法的正确方法是什么? - What is the right way to use Ecmascript 6 arrow functions as methods in classes? ES6 Javascript:使用箭头函数从类中调用静态方法 - ES6 Javascript: Calling static methods from classes with arrow functions 强制 JS 代码对函数、类、它们的方法和粗箭头方法进行注释? - Hot to force JS code to have annotations for functions, classes, their methods and fat arrow methods? 在JavaScript类中混合箭头功能是否有任何弊端? - Are there any drawbacks to mixing arrow functions in javascript classes? 是否可以在 ES6 的类中使用箭头函数? - Is it possible to use arrow functions in classes with ES6? Inheritance 和 JavaScript 类中使用箭头函数的多态性 - Inheritance and polymorphism using arrow functions in JavaScript Classes 与普通的 onClick 函数不同,为什么 React 不渲染没有箭头函数调用的函数的元素? - Why doesn't React render an element without function invoked by arrow function unlike normal onClick functions? 为什么箭头函数可以在ReactJS类上使用而不能在纯ES6类上使用? - Why arrow functions can be used on ReactJS classes but not on a pure ES6 class?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM