首页 > 解决方案 > 根据标志的值编写 React 应用程序

问题描述

问题陈述:

我想编写我的反应应用程序,以根据标志的值使用一组特定的组件。

例如:

默认情况下,我有一个由三个组件组成的 App 组件:

组件 A、组件 B 和组件 C。

<App> 
    <ComponentA />
    <ComponentB />
    <ComponentC />
<App/>

现在,如果我的标志等于 ShowC,我希望我的应用程序呈现 ComponentA、ComponentB 和 ComponentC。

如果标志等于 ShowD,那么我想要渲染 ComponentD 而不是 ComponentC。

<App> 
    <ComponentA />
    <ComponentB />
    <ComponentD />
<App/>

解决方案:

我使用了一个配置对象,该对象具有各自的导入作为键值对:

{
    showC: {
        pos1: ComponentA,
        pos2: ComponentB,
        pos3: ComponentC,
    },
    showD: {
        pos1: ComponentA,
        pos2: ComponentB,
        pos3: ComponentD,
    }
}

现在,在我的主要 App.js 中:

render() {
    const {
        pos1: FirstComponent,
        pos2: SecondComponent,
        pos3: ThirdComponent
    } = config[<flag>];

    <App>
        <FirstComponent />
        <SecondComponent />
        <ThirdComponent />
    </App>
}

我在 stackblitz 上创建了一个简单的示例来说明这一点。

https://stackblitz.com/edit/react-app-components-config?file=index.js

我想了解以这种方式组合组件是否被视为 React 中的反模式?或者是否有更好的解决方案来解决这个问题?

标签: reactjscomponentscomposition

解决方案


您可以创建一个 HOC,它会根据标志决定渲染什么

const DynamicComponent = ({type,children}) => (

  { // you can have any condition here.
    type === 'a'?
    children[0]:
    children[1]
  }

)

// 你的主要组件

render() {

    <App>
        <FirstComponent />
        <SecondComponent />
        <DynamicComponent type={config.type}> 
           <ThirdComponent />
           <FourthComponent />
        </DynamicComponent>
    </App>
}

您应该始终尝试为任何此类组合创建一个新的 HOC,它遵循函数式编程组合模式。


推荐阅读