简体   繁体   English

如何命名 es6 类(用于 React 组件)

[英]How to namespace es6 classes (for React components)

This is part ES6 question part React question.这是部分 ES6 问题部分 React 问题。 I'm trying to use namespaced components in React with ES6 classes and Babel.我正在尝试在带有 ES6 类和 Babel 的 React 中使用命名空间组件 So I guess the real question is how to name space es6 classes so I can do what is explained here: https://facebook.github.io/react/docs/jsx-in-depth.html#namespaced-components所以我想真正的问题是如何命名空间 es6 类,以便我可以做这里解释的事情: https ://facebook.github.io/react/docs/jsx-in-depth.html#namespaced-components

Since I get an unexpected token error:由于我收到意外的令牌错误:

class Headline extends Component { ... }

class Headline.Primary extends Component { ...
              ^

The ECMAScript-6 class declaration syntax expects a standard BindingIdentifer as the class name. ECMAScript-6 类声明语法需要一个标准的BindingIdentifer作为类名。 A dot is not a valid character inside an identifier name.点不是标识符名称中的有效字符。

In the context used in the link in OP, the "namespace" is an object, and properties are added to that object one by one using the dot notation for property access.在 OP 中的链接中使用的上下文中,“命名空间”是一个对象,并且使用用于属性访问的点表示法将属性一个一个地添加到该对象中。

You could replicate that by using a class expression instead:您可以通过使用类表达式来复制它:

 'use strict' var ns = {} ns.MyClass = class { constructor() { console.log('in constructor') } } new ns.MyClass()

This doesn't really change with ES6, you still will have to do an assignment:这在 ES6 中并没有真正改变,你仍然需要做一个赋值:

Headline.Primary = class Primary extends Component { … };

However, using classes like Headline as namespaces is getting pretty deprecated with ES6 (and has previously been a questionable practice anyway), you should instead leverage the new module system.然而,使用像Headline这样的类作为命名空间在 ES6 中已经被弃用了(而且之前一直是一个有问题的做法),你应该改用新的模块系统。 Export Primary as a named export, and instead of importing the Headline class rather do import * as headlines from … .Primary导出为命名导出,而不是导入Headline类,而是import * as headlines from …

This link also relates to this question.链接也与此问题有关。

In the Module objects section, it is described that you can do something like this:Module objects部分,描述了您可以执行以下操作:

// headline.js file
export {Headline, Primary}
class Headline {}
class Primary {}

// In another module...

import * as Headline from "headline";

let h = new Headline.Headline();
let hp = new Headline.Primary();

It's not exactly what you are trying to do, but is an alternative.这并不完全是您想要做的,而是一种替代方法。

Another way of doing it is almost like @Bergi has already pointed out, but I'm just clarifying it further:另一种方法几乎就像@Bergi 已经指出的那样,但我只是进一步澄清它:

let Headline = class Headline extends Component { }
Headline.Primary = class Primary extends Component { }

export {Headline as default}

// in another module:
import Headline from 'headline';

let headline = new Headline();
let primary = new Headline.Primary();

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

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