问题
I seem to be unable to render components using name strings. I wanted to be able to dynamically generate component name strings which have existing corresponding components that can be rendered.
The array
const is going to be populated via JSON data, that's why I need to use string
values for identifying the component.
Here is what I'm trying to do:
import Module1 from './module1';
import Module2 from './module2';
import Module3 from './module3';
const array = ['Module1', 'Module2', 'Module3'];
{array.map((Module, index) =>
<Module />
)}
Instead of referencing the existing component and rendering it, React is rendering a custom element tag that is all lower case.
NOTE: those components ['Module1', 'Module2', 'Module3']
are created as extends Component
回答1:
You can put the components in an object and access them using the strings as keys.
import Module1 from './module1';
import Module2 from './module2';
import Module3 from './module3';
const array = ['Module1', 'Module2', 'Module3'];
const modules = {
Module1,
Module2,
Module3,
};
{moduleOrderArr.map((key, index) => {
const Module = modules[key];
return <Module />;
})}
来源:https://stackoverflow.com/questions/47717326/how-to-render-a-component-by-string-name