首页 > 解决方案 > 根据反应中的组件数组创建包装器

问题描述

我想编写一个函数来根据组件列表生成包装器。在我的应用程序中,我需要根据用户登录阶段加载服务。我想让它有点可配置,使用一个数组来存储服务组件(提供者)。

现阶段

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,但我不知道如何使它正确。

标签: reactjs

解决方案


React.createElement用来处理组件渲染。

function makeWrapper(services) {
  return function(props) {
    return services.reduce(children, Service) {
      return React.createElement(Service, undefined, children);
    }, props.children);
  }
}

推荐阅读