reactjs - 来自 mobx 商店的字符串用作反应组件名称?
问题描述
使用地图感觉有点重复。
有什么方法可以使用从 mobx 传递下来的字符串来渲染反应组件?因为当我有 20 个不同的动态组件时,它很快就会变得混乱和重复。
目前我正在使用:
function ParentComponent(){
const compNames = {
component1: <component1/>,
component2: <component2/>,
}
const component = compNames[store.name];
return(
<div>
<MyComponentName type={type}/>
</div>
)
}
有什么更短的可能吗?例如
function ParentComponent(){
const {name: MyComponentName, type } = store
return(
<div>
<MyComponentName type={type}/>
</div>
)
}
然后将父组件导入索引页面。
解决方案
// MobX store
import UserList from "./UserList";
import UserView from "./UserView";
@observable
component = {
"user-list": UserList,
"user-view": UserView
};
// observer component
@observer function UserComponent({type}) {
const Component = store.component[type];
return <Component />;
}
// display the component
<UserComponent type="user-list" />
推荐阅读
- tcl - 从字符串中获取一个字段,将其存储在一个变量中,然后进行比较
- jwt - 通过服务帐户通过 nodemailer 发送邮件时的身份验证问题
- mysql - 2 count(*)+group by+have+join
- c# - 将传入的 Excel 类型更改为字符串
- git - Jenkins 在尝试从 Bitbucket 结帐时删除了工作区
- session - Laravel + Nginx。会话被随机访问
- bash - 如何从带有保留空格的管道(|)分隔文件中读取字段
- json - 如何连接来自不同 nosql 集合的两个数组?
- printing - 根据列值在每一页上打印标题 - 数据表
- parsing - 有没有办法在宏中实现可选表达式?