如何通过字符串名称呈现组件 [英] how to render a component by string name

查看:84
本文介绍了如何通过字符串名称呈现组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法使用名称字符串来渲染组件。我希望能够动态生成具有可以呈现的现有对应组件的组件名称字符串。

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.

数组 const将通过JSON数据填充,这就是为什么我需要使用 string 值来标识组件的原因。

The array const is going to be populated via JSON data, that's why I need to use string values for identifying the component.

这就是我想要做的:

import Module1 from './module1';
import Module2 from './module2';
import Module3 from './module3';

const array = ['Module1', 'Module2', 'Module3'];

{array.map((Module, index) =>
 <Module />
)}

React而不是引用现有组件并对其进行渲染,而是渲染了一个全部为小写的自定义元素标签。

Instead of referencing the existing component and rendering it, React is rendering a custom element tag that is all lower case.

注意:这些组件 ['Module1','Module2','Module3'] 是在扩展组件

推荐答案

您可以将组件放在对象中,并使用字符串作为键来访问它们。

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 />;
})}

这篇关于如何通过字符串名称呈现组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆