首页 > 解决方案 > 如何在反应中有通用的打字稿道具?打字稿通用道具不起作用

问题描述

这就是我想要做的反应,

我有一个功能组件,我在其中传递了 1 个道具

<TableComponent tableStateProp={tableState} />

tableState 是父组件中的状态钩子

  const [tableState, setTableState] = useState<TableState<string[]>>();

表状态类型是在我的表组件中定义的

export type TableState<T> = {
  pagination: {
    limit: number,
    skip: number,
  }
  data: T[];
  columns: string[],
}

但这是我的问题开始的地方,理想情况下我可以做到这一点

const TableComponent: React.FC<{
  tableState: TableState<T>;
}> = ({tableState}) => {

但我得到一个错误说TS2304: Cannot find name 'T'.

我知道通用道具函数的语法类似于function<T>(): type<T> 但通用道具/对象是什么?

编辑:我在数据不是字符串 [] 的其他地方使用这个组件,因此我试图使其通用

谢谢

标签: javascriptreactjstypescript

解决方案


你不需要使用React.FC<>. 将您的组件声明为命名函数,您可以添加通用的<T>.

export type TableState<T> = {
  pagination: {
    limit: number;
    skip: number;
  };
  data: T[];
  columns: string[];
};

function TableComponent<T>({
  tableState,
}: React.PropsWithChildren<{
  tableState: TableState<T>;
}>) {
  // ...
}

如果您不需要children道具工作,您也不需要使用React.PropsWithChildren,只需:

function TableComponent<T>({ tableState }: { tableState: TableState<T> }) {

如果您想在TableComponent级别上明确返回类型(而不是稍后在应用程序中使用它时),您可以查看React.FC正在执行的操作并相应地明确输入:

function TableComponent<T>({
  tableState,
}: {
  tableState: TableState<T>;
}): ReactElement<any, any> | null {
  return null;
}

推荐阅读