![](/img/trans.png)
[英]How to use an array containing some component names to render those predefined components
[英]How make a predefined filtered array list reusable, to use in multiple React components
我們從 api ( NodeTypeOne
、 NodeTwo
、 NodeTypeThree
)中獲得了多種節點類型(預告片)。
NodeTypeOne
和NodeTypeThree
。<NodeTypeOne />
和<NodeTypeThree />
創建了子組件,它們返回一些類似的道具(如標題和標簽)但也有一些不同的道具(基於節點類型: <NodeTypeThree tag={nodeTypeThree.tag} />
目前我正在使用它:
const MyBlock = ({ data }: Props) => {
const filteredItems = data.items?.filter(
(item) =>
item?.__typename.includes("NodeTypeOne") || item?.__typename.includes("NodeTypeThree")
);
return data?.items?.length ? (
<Block>
{filteredItems.map((node) => {
if (node.type.includes("NodeTypeOne")) {
const teaserOne = node as TeaserTypeOne;
return (
<TeaserOne
key={teaserOne.id}
title={teaserOne.title}
subtitle={teaserOne.subtitle}
/>
);
}
const teaserTypeThree = node as TeaserTypeThree;
return (
< TeaserThree
key={teaserTypeThree.id}
title={teaserTypeThree.title}
subtitle={teaserTypeThree.subtitle}
tag={teaserTypeThree.tag}
/>
);
})}
</Block>
) : null;
};
export default MyBlock;
如何使上述邏輯可重用?
例如,在某些情況下,我必須添加其他道具來創建不同的樣式等:
if (node.type.includes("NodeTypeOne")) {
const teaserOne = node as TeaserTypeOne;
return (
<TeaserOne
key={teaserOne.id}
title={teaserOne.title}
subtitle={teaserOne.subtitle}
anotherProp={anotherProp} // <- this one is added here
/>
);
}
const teaserTypeThree = node as TeaserTypeThree;
return (
< TeaserThree
key={teaserTypeThree.id}
title={teaserTypeThree.title}
subtitle={teaserTypeThree.subtitle}
tag={tag}
anotherProp={anotherProp} // <- this one is added here
/>
);
這里有什么好方法?
您可以將組件分配給變量,因此在您的情況下它將是:
const Component = node.type.includes("NodeTypeOne") ? TeaserOne : TeaserThree;
return (
< Component
key={teaserTypeThree.id}
title={teaserTypeThree.title}
subtitle={teaserTypeThree.subtitle}
tag={teaserTypeThree.tag}
/>
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.