我需要根据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 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()
);
}
}
//这是我用来通过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>
);
}
};
}
答案 0 :(得分:0)
显然,如果它们是动态地来自同一文件,则无法获得命名的导出,因此解决方案是导入这些文件并在componentDidMount上获取变量。