reactjs - 根据标志的值编写 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 中的反模式?或者是否有更好的解决方案来解决这个问题?
解决方案
您可以创建一个 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,它遵循函数式编程组合模式。
推荐阅读
- algorithm - 当某些点被阻挡时到达终点的最小跳跃
- sorting - 验证Shell Sorting算法循环不变量?
- php - 排列关联数组中的数据
- visual-studio-code - 如何通过右键单击打开 VSCode Remote-WSL
- bash - cURL:管理下载错误
- python - 使用 group by 后如何将结果保存为数据框
- shell - 循环监听代码不适用于 Shuttler 按钮
- c# - 如何在不循环的情况下将 LINQ 查询结果分组到 DataGridView
- html - 如果 HTML 表格太大,则直到下一页才会开始
- haskell - 如何在 haskell 中获取元组的索引?