如何使用索引文件导入的命名空间动态调用模块



我正在尝试将前端设置为根据客户需求动态调用组件的应用程序。因此,我们有一个索引文件,其中三个组件正在导入ComponentOne ComponentTwo ComponentThree

我像这样导入它, import * as components from '../components'

然后,在我的渲染方法中,我有一个称为ComponentString的Prop(从母体组件传递(,该Prop用于检查该站点的用户版本上是否应存在组件是否存在。

例如,此组件字符串将为" componentone"。我有一个包装器,可以检查用户后端上是否存在特定组件,然后应致电并渲染该组件。

我的问题是我如何使用此字符串基本调用组件。

我尝试了诸如<components[componentString] /><components.componentString />{component[componentString]}之类的事情,最后是{components.componentString]}。所有这些都无法正常工作,从本质上讲,我希望结果与<ComponentOne />相等,但是称<componentString />之类的内容也不起作用。

从官方反应文档中获取,我会说您需要像以下内容一样写它。基本上,您需要在尝试渲染之前将其添加为CapitalizedComponent

import React from 'react';
import { PhotoStory, VideoStory } from './stories';
const components = {
  photo: PhotoStory,
  video: VideoStory
};
function Story(props) {
  // Correct! JSX type can be a capitalized variable.
  const SpecificStory = components[props.storyType];
  return <SpecificStory story={props.story} />;
}

您是否尝试过:

// Outside class/function
const MyComponent = Components.componentString;
// ....render
<MyComponent />

最新更新