简体   繁体   English

如何使用命名导入动态加载不同的组件

[英]How to dynamically load different components with named imports

I need to use a different component depending on a propType, as a first attempt I'm using an object to store the components I need the problem is that It only works for the first key, for example it only works for AvatarList.Item, when I try to load Avatar.List it just doesn't load. 我需要根据propType使用不同的组件,第一次尝试使用对象存储组件时,我需要的问题是它仅适用于第一个键,例如,仅适用于AvatarList.Item,当我尝试加载Avatar.List时,它不会加载。

const component = {
  AvatarList: {
    Item: async () => (await import('../List/Avatar')).Avatar,
    List: async () => (await import('../List/Avatar')).List,
  },
  Simple: {
    List: async () => (await import('../List/Simple')).List,
    Item: async () => (await import('../List/Simple')).Simple,
  },
};

// Here there is the component and the default I componentType is "AvatarList" //这里是组件,默认的I componentType是“ AvatarList”

class Articles extends Component {
  renderListItem() {
    const { componentType, newsArticles } = this.props;
    const Item = importComponent(component[componentType].Item);
    return newsArticles.map(({
      url,
      id,
      imageUrl,
      title,
      description,
    }) => (
      <Item
        id={id}
        url={url}
        imageUrl={imageUrl}
        title={title}
        description={description}
      />
    ));
  }

  renderList() {
    const { componentType } = this.props;
    const List = importComponent(component[componentType].List);
    return (
      <List>
        {this.renderListItem()}
      </List>
    );
  }

  render() {
    return (
      this.renderList()
    );
  }
}

// This is the HOC I use for the loading the components with async/await //这是我用于通过async / await加载组件的HOC

import React, { Component } from 'preact-compat';

import Loader from '../components/Loader/Loader';

export default function importComponent(importFunction) {
  return class ComponentImporter extends Component {
    async componentWillMount() {
      this.setState({ component: await importFunction() });
    }

    render() {
      const ImportedComponent = this.state.component;

      return (
        <Loader loaded={Boolean(this.state.component)}>
          <ImportedComponent {...this.props} />
        </Loader>
      );
    }
  };
}

显然,如果它们是动态地来自同一文件,则无法获取命名的导出,因此解决方案是导入这些文件并在componentDidMount上获取变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM