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



我需要根据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,
},
};

//这里有一个组件,默认的I组件类型是"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()
);
}
}

//这是我用来加载异步/等待组件的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>
);
}
};
}

显然,如果命名导出动态地来自同一个文件,我就无法获得它们,所以解决方案只是导入这些文件并在组件DidMount上获取变量。

最新更新