reactjs - 根据反应中的组件数组创建包装器
问题描述
我想编写一个函数来根据组件列表生成包装器。在我的应用程序中,我需要根据用户登录阶段加载服务。我想让它有点可配置,使用一个数组来存储服务组件(提供者)。
现阶段
function App() {
return (
<DndService>
<SubscriptionService> // activated only if user login
<IMService> // activated only if user login
<AppRender />
</IMService>
</SubscriptionService>
</DndService>
);
}
预期的:
const services = hasLogin ? [DndService, SubscriptionService, IMService] : [DndService];
const ServiceWrap = makeWrapper(services);
function App() {
return (
<ServiceWrap>
<AppRender />
</ServiceWrap>
);
}
我认为makeWrapper
应该做类似的事情compose
,但我不知道如何使它正确。
解决方案
我React.createElement
用来处理组件渲染。
function makeWrapper(services) {
return function(props) {
return services.reduce(children, Service) {
return React.createElement(Service, undefined, children);
}, props.children);
}
}
推荐阅读
- virtual-machine - 如何在 Virtual-Box 的 iOS(主机)中使访客(Windows 10)全屏
- python - 在 ajax 站点中查找页码以进行 Web Scraping
- java - 帕斯卡三角 II:Java:它可以在 O(1) 空间复杂度中完成吗?
- python - 如何从 Django 模型中继承和过滤数据
- javascript - 如何在 React Native 的 Flatlist 中传递数组以渲染
- angular - “EventTarget”类型上不存在属性“scrollTop”。[已弃用]
- lua - 罗技鼠标重复切换
- java - PDFBox - 防止注释出现在叠加层之上
- c# - 不区分大小写地比较 C# 中的 HashTable 键
- c++ - 如何解决路径上的“未找到类“...”:我对 Java 的本机回调中的 DexPathList