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

rel*_*don 8 reactjs

我想做这个

src/modules/layout/nav.js

...
export default NavBar;
Run Code Online (Sandbox Code Playgroud)

src/modules/layout/side.js

...
export default sideBar;
Run Code Online (Sandbox Code Playgroud)

src/modules/layout/index.js

import NavBar from './nav';
import sideBar from './side';
export { NavBar, sideBar };
Run Code Online (Sandbox Code Playgroud)

src/modules/index.js

import * from './layout';
Run Code Online (Sandbox Code Playgroud)

最后一点不起作用.根据教程,我可以去,src/App.js并使用navBar如下:

从'./modules'导入{navBar};

但事实是*不起作用我不能这样做.有什么选择,不必像这样

src/modules/index.js

import * as All from './layout';
export All;
Run Code Online (Sandbox Code Playgroud)

然后在App.js,走All.navBar.那感觉很难看

小智 15

好吧,我已经完成了你所拥有的; 我觉得你真正需要的是理解这样做的原因.我很确定你想要实现的是从单个文件而不是导出组件的文件中导入组件.

You don't want to do this:

import NavBar from 'src/modules/layout/NavBar';
import SideBar from 'src/modules/layout/SideBar';
Run Code Online (Sandbox Code Playgroud)

但您想要的是从单个文件导入所有组件,无论您希望在何处使用它们.因此,如果是这种情况,则无需添加更多复杂性.你只需要做的就是:

// 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. 
Run Code Online (Sandbox Code Playgroud)

所以,我相信这会回答你的问题.


Att*_*que 14

只是为了添加 Onyekachi Samuel 的答案并回答标题的所有部分:

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>)
}
Run Code Online (Sandbox Code Playgroud)

希望这可以为某些人澄清它。