簡體   English   中英

如何使預定義的過濾數組列表可重用,以在多個 React 組件中使用

[英]How make a predefined filtered array list reusable, to use in multiple React components

我們從 api ( NodeTypeOneNodeTwoNodeTypeThree )中獲得了多種節點類型(預告片)。

  • 這些節點類型呈現在多個地方,作為我的 React 應用程序中的列表。 我只需要在列表中渲染NodeTypeOneNodeTypeThree
  • 我還為那些節點類型預告片<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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM