how to render a component by string name

别等时光非礼了梦想. 提交于 2020-01-03 17:49:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!