为什么es6反应组件仅与“export default”有关? [英] Why es6 react component works only with "export default"?

查看:186
本文介绍了为什么es6反应组件仅与“export default”有关?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此组件可以正常工作:

export class Template extends React.Component {
    render() {
        return (
            <div> component </div>
        );
    }
};
export default Template;

如果我删除最后一行,则不起作用。

If i remove last row, it doesn't work.

Uncaught TypeError: Cannot read property 'toUpperCase' of undefined

我猜,我不明白es6语法的东西。是不是没有输出没有符号默认?

I guess, I don't understand something in es6 syntax. Isn't it have to export without sign "default"?

推荐答案

导出为 default 表示它是命名导出。您可以在单个文件中具有多个命名导出。所以如果你这样做,那么

Exporting without default means it's a "named export". You can have multiple named exports in a single file. So if you do this,

export class Template {}
export class AnotherTemplate {}

那么您必须使用其确切名称导入这些导出。所以要在另一个文件中使用这些组件,

then you have to import these exports using their exact names. So to use these components in another file you'd have to do,

import {Template, AnotherTemplate} from './components/templates'

或者如果您导出为默认值导出这样,

Alternatively if you export as the default export like this,

export default class Template {}

然后在另一个文件中导入默认导出而不使用 {} ,像这样,

Then in another file you import the default export without using the {}, like this,

import Template from './components/templates'

每个文件只能有一个默认导出。在React中,这是一个约定,从文件导出一个组件,并将其导出为默认导出。

There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.

您可以在导入时重命名默认导出它,

You're free to rename the default export as you import it,

import TheTemplate from './components/templates'

您可以同时导入默认和命名导出,

And you can import default and named exports at the same time,

import Template,{AnotherTemplate} from './components/templates'

这篇关于为什么es6反应组件仅与“export default”有关?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆