首页 > 解决方案 > 键入 React 组件实例的数组

问题描述

我有一个表格组件,它接收一个字符串/数字数组的数组作为道具,所以它需要一个rows像这样键入的参数:

type Row = (string | number)[];

但是,有些列需要显示 React 组件而不是纯文本/数字。

如何更改类型以使其正常工作?我试过这个:

type Row = (string | number | React.PureComponent | React.Component)[];

标签: reactjstypescripttypescript-typings

解决方案


这里有许多可行的选项,其中一些比其他选项更好,具体取决于您如何使用它们。我一直在使用React.ReactNode它来指定孩子,但您也可以将它用于您的用例。

type Row = (string | number | React.ReactNode)[];

ReactNode非常灵活,因为它被定义为:

type ReactNode = ReactChild | ReactFragment | ReactPortal | boolean | null | undefined;

ReactChild反过来,定义为:type ReactChild = ReactElement | ReactText;

如果您希望它更严格、更不灵活,请尝试ReactElement.


推荐阅读