Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - React如何导出组件? 命名与默认(How is Component exported with React? Named vs Default)

I've seen this syntax in many files:

(我在许多文件中都看到了这种语法:)

import React, {Component} from react;

I understand how named exports and default exports work separately but I'm not sure how React handles this when it is exporting it's code.

(我知道命名导出和默认导出是如何分别工作的,但是我不确定React在导出代码时如何处理它。)

For instance is the default React export an object which contains the Component as a named export function?

(例如,默认的React export是一个包含Component作为命名导出函数的对象吗?)

which is why you can use the React.Component dot notation?

(这就是为什么您可以使用React.Component点表示法的原因?)

  ask by j obe translate from so

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

1 Answer

0 votes
by (71.8m points)

If you dig a few files deeper into React's source code, you'll find this file where the React object we import many times a day is constructed and exported.

(如果您深入研究React的源代码中的几个文件,您会发现该文件是我们每天多次导入的React对象在其中构建和导出的。)

At line 66 :

(在第66行 :)

const React = {
   ...
   // just a few examples of what's in here...
   Component,
   useState,
   Fragment,
   ...
}

And then by the end of this file, the object is exported as the default export.

(然后,在此文件末尾,该对象将作为默认导出导出。)

Inside this object, you'll find many familiar components/methods, including Component , Fragment , useState , etc. These are declared as properties of the React object, which is why we can:

(在此对象内,您会发现许多熟悉的组件/方法,包括ComponentFragmentuseState等。这些被声明为React对象的属性,因此我们可以:)

  • Use them using dot notation React.Component when the entire React object is imported

    (导入整个React对象时,使用点符号React.Component来使用它们)

And as part of the React object, they are exported implicitly , which is why we can:

(并且作为React对象的一部分,它们被隐式导出,这就是为什么我们可以:)

  • Import them using import {Component} from 'react'

    (使用import {Component} from 'react'导入它们)

Component is not a named export in the module (there is only one export statement in the module and that is default export).

(Component不是模块中的命名导出(模块中只有一个export语句,这是默认导出)。)

Though the import statement does make it look like one.

(尽管import语句确实使它看起来像一个。)

Hope this helps!

(希望这可以帮助!)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...