首页 > 解决方案 > 来自 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>
  )
}

然后将父组件导入索引页面。

标签: reactjsmobxmobx-react

解决方案


// 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" />

推荐阅读