我正在尝试将前端设置为一个应用程序,该应用程序可根据客户需要动态调用组件。所以我们有一个索引文件,其中包含三个正在导入的组件 ComponentOne ComponentTwo ComponentThree
我是这样导入的,import * as components from '../components'
然后在我的 render 方法中,我有一个名为 componentString 的 Prop (从父组件传递),它主要用于检查该组件是否应该存在于网站的这个用户版本上。
例如,此组件字符串将为“ComponentOne”。我有一个包装器,用于检查特定组件是否存在于用户的后端,然后应该调用并呈现该组件。
我的问题是如何使用这个字符串来调用组件。
我试过类似 <components[componentString] />
的东西或 <components.componentString />
或 {component[componentString]}
最后 {components.componentString]}
.都不起作用,基本上我只是希望结果等于 <ComponentOne />
但调用类似 <componentString />
的东西也不行。
最佳答案
摘自官方react docs我会说你需要像下面这样写。基本上,您需要在尝试呈现它之前将其添加为 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} />;
}
关于javascript - 如何使用从索引文件导入的命名空间动态调用模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56757945/