代码之家  ›  专栏  ›  技术社区  ›  Pranita

基于标志的值编写React应用程序

  •  1
  • Pranita  · 技术社区  · 7 年前

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

    例如:

    <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,
        }
    }
    

    现在,在我的主应用程序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中的反模式?或者是否有更好的解决办法?

    1 回复  |  直到 7 年前
        1
  •  1
  •   hannad rehman    7 年前

    可以创建一个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>
    }
    

    推荐文章