有人能告诉我如何使用.map导入一组组件吗?就像这样..。
import Welcome from 'Welcome.jsx';
import Services from 'Services.jsx';
const Index = props => {
const myComponents = ['Welcome', 'Services'];
return (
<div>
{myComponents.map((componentName, index) => (
<div key={index}> />
<{componentName} />
</div>
))}
</div>
);
};```发布于 2019-11-19 00:23:54
别用他们的名字。在数组中使用组件(函数值)本身:
import Welcome from 'Welcome.jsx';
import Services from 'Services.jsx';
const Index = props => {
const myComponents = [Welcome, Services];
return (
<div>
{myComponents.map((AnyComponent, index) => (
<div key={index}> />
<AnyComponent />
</div>
))}
</div>
);
};发布于 2019-11-19 00:26:14
你可以试试@Bergi解决方案。但是,您也可以使用require导入和生成组件。
const myComponents = ['Welcome', 'Services'].map((name) => require(`${name}.jsx`).default);
const Index = props => {
return (
<div>
{myComponents.map((component, index) => {
const Component = component;
return (
<div key={index}>
<Component />
</div>
);
})}
</div>
);
};发布于 2019-11-19 00:30:09
通过延迟加载组件,您可以更进一步:
const OtherComponent = React.lazy(() => import('./OtherComponent'));
const AnotherComponent = React.lazy(() => import('./AnotherComponent'));
const MyComponent () => {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<section>
<OtherComponent />
<AnotherComponent />
</section>
</Suspense>
</div>
);
}https://stackoverflow.com/questions/58924851
复制相似问题