[英]Using .map in return() to import a component
谁能告诉我如何使用.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>
);
};```
不要用他们的名字 go。 在数组中使用组件(函数值)本身:
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>
);
};
您可以尝试@Bergi 解决方案。 但是,您也可以 go 完全通用并使用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>
);
};
您可以通过延迟加载组件更进一步:
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>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.