我有一个接收属性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,
};
您快到了,您也只需通过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].