带有React渲染道具的Flow泛型

问题描述 投票:3回答:1

我有一个接收属性items的组件,该属性定义为任何类型的数组。它遍历此数组,可以在数组中的每个项目上调用prop render

type ResultCardsProps = {
  items: *[],
  render: * => Node,
};

const ResultCards = ({ items, render, ...props }: ResultCardsProps) => (
  <div {...props}>
    {items.map(render)}
  </div>
);

这是我如何使用此组件的示例:

type Sport = { id: number, name: string };
type Props = { sports: Sport[] };

const SportsCards = ({ sports }: Props) => (
  <ResultCards
     items={sports}
     render={sport => <div>{sport.name}</div>} // Flow does not know the type for `sport` at this point
  />
);

是否有一种方法可以使Flow理解render组件中传递给SportsCard函数的类型?如果组件在同一文件中,则does工作,但是当将组件放入不同文件中时,它停止工作。我尝试对ResultCardsProps使用泛型,但没有什么不同:

type ResultCardsProps<T> = {
  items: T[],
  render: T => Node,
};
javascript reactjs types flowtype
1个回答
0
投票

您快到了,您也只需通过ResultCards组件签名传递通用类型:

const ResultCards = <T>({ items, render, ...props }: ResultCardsProps<T>) => (
  <div {...props}>
    {items.map(render)}
  </div>
);

const SportsCards = ({ sports }: Props) => (
  <ResultCards
    items={sports}
    render={sport => (
      <div>
        {sport.name}
        <div>{sport.foo}</div>
      </div>
    )}
  />
);

// The above generates this Flow error:
// ^ Cannot get `sport.foo` because property `foo` is missing in `Sport` [1].

(Flow REPL)

© www.soinside.com 2019 - 2024. All rights reserved.