简体   繁体   English

React,如何从文件夹 index.js 导入组件

[英]React, how to import components from folder index.js

I have a little component library I am trying to build out.我有一个正在尝试构建的小组件库。 So it made sense to put them in a folder and only import the ones I need or all at once if needed using the import * from folder.因此,将它们放在一个文件夹中并且只导入我需要的那些或在需要时使用 import * from folder 一次导入是有意义的。

It looks a little something like this.它看起来有点像这样。

 /sliceZone
 |--index.js
 |--newsBlock.js

This is how I'm exporting my component in newsBlock.js:这就是我在 newsBlock.js 中导出组件的方式:

export default NewsBlock;

Inside my index.js in the sliceZone folder I have:在 sliceZone 文件夹中的 index.js 中,我有:

export { NewsBlock } from './newsBlock';

and inside the file Im working on I am trying to import it like:在我正在处理的文件中,我试图像这样导入它:

import { NewsBlock } from './sliceZone';

But I'm getting the error in my terminal但我的终端出现错误

warn "export 'NewsBlock' was not found in './sliceZone'

How do I export components from a index.js file?如何从index.js文件中导出组件?

On your index.js file you should try在您的index.js文件中,您应该尝试

export {default as NewsBlock} from './newsBlock';

Whenever you have a default export, you need not destructure it in import statements.只要有默认导出,就不需要在导入语句中对其进行解构。 So if you have所以如果你有

export default NewBlock;

You can import it using您可以使用导入它

import NewsBlock from ./newsBlock;
import Anything from ./newsBlock;

Both above statements are valid.上述两种说法均有效。 And NewsBlock and Anything imports will have NewsBlock.并且NewsBlockAnything导入都会有 NewsBlock。

If you export object as below如果您导出 object 如下

export NewsBlock;

Then you must destructure it to use.然后你必须解构它才能使用。

import {NewsBlock} from ./newsBlock;

Not sure if it is something you are looking for, but just felt it is related information and may solve your issue.不确定它是否是您正在寻找的东西,但只是觉得它是相关信息并且可能会解决您的问题。

inside newsBlock.js you can write export default NewsBlock;newsBlock.js ,您可以编写export default NewsBlock; and you can import that from import { NewsBlock } from './sliceZone';你可以从import { NewsBlock } from './sliceZone'; or import { NewsBlock } from './sliceZone/index';import { NewsBlock } from './sliceZone/index';

I managed to figure it out.我设法弄清楚了。

In index.js在 index.js 中

import NewsBlock from './newsBlock';
//Anything else to import from the folder.

export { NewsBlock, /*Anything else to export*/ };

then when I import into another file I can use.然后当我导入另一个文件时,我可以使用。

import { NewsBlock, /*Anything else*/ } from './sliceZone/';

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

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