如何在React中导入所有组件?

19

我想在 src/modules/layout/nav.js 中完成这个任务。

...
export default NavBar;

src/modules/layout/side.js 中:
...
export default sideBar;

src/modules/layout/index.js 中:
import NavBar from './nav';
import sideBar from './side';
export { NavBar, sideBar };

src/modules/index.js 中:
import * from './layout';

最后一步无法运行。按照教程,我应该能够转到 src / App.js 并使用 navBar 如下:

从'./modules'导入{navBar}

但是,由于*无法工作,我不能这样做。是否有其他替代方案,而无需像此类那样进行操作?

src/modules/index.js中。

import * as All from './layout';
export All;

然后在 App.js 文件中,进入 All.navBar。这感觉很丑。
2个回答

35

好的,我已经看了你所提供的内容;我觉得你实际上需要了解为什么要这样做。我非常确定你想要实现的是从一个单独的文件中导入组件,而不是从导出组件的文件中导入。

你不想这样做:

import NavBar from 'src/modules/layout/NavBar';
import SideBar from 'src/modules/layout/SideBar';

但是你想要的是从一个单独的文件中导入所有组件,无论在哪里使用它们。

因此,如果是这种情况,你不需要添加更多复杂性。你所需要做的就是:

// export the components like this
export default NavBar;
export default SideBar;

// Then, in your src/modules/layout/index.js file, import // the components you exported just the way you did it

import NavBar from './NavBar';
import SideBar from './SideBar';

export {
NavBar,
SideBar
}

// Hence, wherever you need both components, you can easily do this:
import { NavBar, SideBar } from '../index.js'

// From the above, you are just importing both components from the index.js file. 

所以,我相信这回答了你的问题。


谢谢。非常好的解释。非常有效! - AO19
在你的 src/modules/layout/index.js 中,你可以简单地使用 export NavBar from './NavBar';,而不是使用 import 和 export。 - Joel

25

仅是为了补充Onyekachi Samuel的回答并回答标题中的all部分:

按照他描述的步骤将创建src/modules/layout/index.js文件后,你可以通过以下方式导入全部内容:

import * as All from './layout'

并使用所导出的组件:

<All.NavBar/> <All.SideBar/>

例如:

// Folder structure:
//    |-App.js
//    |-Layout
//        |-NavBar.js
//        |-SideBar.js
//        |-index.js


// App.js in the same location as Layout folder

import React from 'react';
import * as All from './layout'

export default function App(props) {

    return (<div>
                <All.NavBar/>
                <All.SideBar/>
           </div>)
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接