简体   繁体   English

使用Babel将Arrow用作类属性

[英]Arrow functions as class properties using Babel

Can someone explain how Babel in React supports fat arrow functions as class properties? 有人可以解释一下React中的Babel如何支持粗箭头功能作为类属性吗? Using Babel Try it out I can see they are not supported: 使用Babel 尝试一下,我可以看到它们不受支持:

class Question {

  // Property (not supported)
  myProp = () => {
    return 'Hello, world!';
  }

  // Method (supported)
  myFunc() {
    return 'Hello, world!';
  }

}

Class properties are not supported in ES6 (correct me if I'm wrong) but then in React (with Babel) they work. ES6不支持类属性(如果我错了,请纠正我),但是在React(使用Babel)中它们可以工作。

I can see the difference between methods and properties using TypeScript Playground but I can't clearly understand if Babel is supporting them or not. 我可以使用TypeScript Playground看到方法和属性之间的区别,但是我不清楚Babel是否支持它们。 Is there some plug-in? 有插件吗?

UPDATE: 更新:
I can see they are supported using "babel-preset-stage-0" . 我可以使用"babel-preset-stage-0"支持它们。

To support class properties, you need to install and add babel-plugin-transform-class-properties to the plugins setting of your .babelrc (or in your webpack config). 为了支持类属性,您需要安装babel-plugin-transform-class-properties并将其添加到.babelrcplugins设置中(或在webpack配置中)。

Note that this plugin is also included in 请注意,此插件也包含在

So if you use one of those, you don't need to install babel-plugin-transform-class-properties by yourself. 因此,如果您使用其中之一,则无需自己安装babel-plugin-transform-class-properties

As @illiteratewriter suggested class properties are supported from Stage 0 preset . 正如@illiteratewriter建议的那样,从Stage 0预设支持类属性。 For the time being, they are supported until Stage 2 preset : 目前,它们在阶段2预设之前一直受支持:

The proposal must now additionally have a formal description of the syntax and semantics of the feature (using the formal language of the ECMAScript specification). 现在,该提案还必须对功能的语法和语义进行正式描述(使用ECMAScript规范的正式语言)。 The description should be as complete as possible, but can contain todos and placeholders. 说明应尽可能完整,但可以包含待办事项和占位符。 Two experimental implementations of the feature are needed, but one of them can be in a transpiler such as Babel. 需要对该功能进行两个实验性的实现,但是其中一个可以在诸如Babel的编译器中进行。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM