嗨,我想从一个目录动态加载多个 react 组件。这样某人只需在目录中添加一个组件即可加载它。我在想类似的事情:
import * as dynamicComponents from './dynamicComponents';
const toAdd = [] dynamicComponents.forEach(function(component){
toAdd.push( Route path={component.link} component={component.implmentation} /> })
render(<Provider store={store}>
<Router history={history}>
<Route path="/" component={Template}>
<IndexRoute component={Main} />
{toAdd}
</Route>
</Router>
</Provider>,
document.getElementById('root') );
这可能吗?
最佳答案
我相信你的第一个 import 语句在 Babel 中不起作用。试试这个包:
npm i --save-dev babel-plugin-wildcard
将其添加到您的 .babelrc 中:
{
"plugins": ["wildcard"]
}
您的环境中可能没有使用 Babel,但本质上您需要解决从通配符或动态路径加载的问题。这可能是最困难的部分。
您还需要确保放入目录中的每个文件都导出 React 组件类作为其默认导出,并且具有返回链接的静态函数。
const SomeReactComponent = () => (<p>Rendering something.</p>);
//Export link as static member of the class.
SomeReactComponent.link = '/some/react/component/routing/link';
export default SomeReactComponent;
然后像下面这样的代码将在编译时运行:
import * as dynamicComponents from './dynamicComponents';
const toAdd = dynamicComponents.map( (ComponentClass) => <Route path={ComponentClass.link} component={ComponentClass} /> );
这是一个编译时解决方案。如果您想要一个运行时解决方案,请研究使用 ES6 导入以外的导入器,我认为 ES6 导入不能在运行时动态使用。
关于node.js - 如何动态加载多个React组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43946537/