问题描述
我有一个页面根据用户输入呈现不同的组件。目前,我已对每个组件的导入进行了硬编码,如下所示:
I have a page which renders different components based on user input. At the moment, I have hard coded the imports for each component as shown below:
import React, { Component } from 'react'
import Component1 from './Component1'
import Component2 from './Component2'
import Component3 from './Component3'
class Main extends Component {
render() {
var components = {
'Component1': Component1,
'Component2': Component2,
'Component3': Component3
};
var type = 'Component1'; // just an example
var MyComponent = Components[type];
return <MyComponent />
}
}
export default Main
但是,我一直在更改/添加组件。有没有办法可能有一个文件只存储组件的名称和路径,然后这些文件在另一个文件中动态导入?
However, I change/add components all the time. Is there a way to perhaps have a file which stores ONLY the names and paths of the components and these are then imported dynamically in another file?
推荐答案
我认为对于我想要实现的目标可能存在一些困惑。我设法解决了我遇到的问题,并在下面显示了我的代码,显示了我是如何解决它的。
I think there may have been some confusion as to what I was trying to achieve. I managed to solve the issue I was having and have shown my code below which shows how I solved it.
单独的文件(ComponentIndex.js):
Separate File (ComponentIndex.js):
let Components = {};
Components['Component1'] = require('./Component1').default;
Components['Component2'] = require('./Component2').default;
Components['Component3'] = require('./Component3').default;
export default Components
主文件(Main.js):
Main File (Main.js):
import React, { Component } from 'react';
import Components from './ComponentIndex';
class Main extends Component {
render () {
var type = 'Component1'; // example variable - will change from user input
const ComponentToRender = Components[type];
return <ComponentToRender/>
}
}
export default Main
此方法允许我非常快速地添加/删除组件,因为导入在一个文件中,并且一次只需要更改一行。
This method allows me to add/remove components very quickly as the imports are in one file and only requires changing one line at a time.
这篇关于反应 - 动态导入组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!