Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

javascript - 为什么es6反应组件仅适用于“导出默认值”?(Why es6 react component works only with “export default”?)

This component does work:

(该组件确实有效:)

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

I guess, I don't understand something in es6 syntax.

(我想,我不明白es6语法中的一些东西。)

Isn't it have to export without sign "default"?

(是不是必须导出没有“默认”的标志?)

  ask by stkvtflw translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Exporting without default means it's a "named export".

(无default导出意味着它是“命名导出”。)

You can have multiple named exports in a single file.

(您可以在单个文件中具有多个命名导出。)

So if you do this,

(所以,如果你这样做,)

class Template {}
class AnotherTemplate {}

export { Template, 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,

(或者,如果您导出为此default导出,)

export default class Template {}

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

(然后在另一个文件中导入默认导出而不使用{} ,如下所示,)

import Template from './components/templates'

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.

(在React中,从文件中导出一个组件是一种约定,并将其导出为默认导出。)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...