【问题标题】:table data and column type (react-table v8)表数据和列类型(react-table v8)
【发布时间】:2022-08-19 14:49:02
【问题描述】:

我对打字稿相当陌生,我正在使用@tanstack/react-table 并在useReactTable 钩子周围构建了一个TableComponent,它需要2 个道具data 和columns 并将它们传递给useReactTable 钩子。

问题是数据和列道具是可以包含不同类型对象的数组并且它们是连接的,我怎样才能正确输入它们?现在我在TableComponent 中遇到错误

type OrderTableProps = {
  data: OrdersRow[];
  columns: typeof ordersTableColumns;
  onRowClick?: (row: Row<OrdersRow>) => void;
}

type ContainerTableProps = {
  data: ContainersRow[];
  columns: typeof containersTableColumns;
  onRowClick?: (row: Row<ContainersRow>) => void;
}

export type TableComponentProps = PropsWithChildren
  & TableComponentBaseProps
  & (OrderTableProps | ContainerTableProps);
    

// TableComponent
    const ReactTableComponent = ({data, columns}: TableComponentProps) => {
     const table = useReactTable({
        data, -> Type \'OrdersRow[] | ContainersRow[]\' is not assignable to type \'OrdersRow[]\'
        columns,
        getCoreRowModel: getCoreRowModel(),
      });
    
      return (
        <Table> ... </Table>

}

    标签: reactjs typescript react-table


    【解决方案1】:

    您需要的是具有泛型类型的 Table 组件。我们开始做吧。

    例如表组件名称为反应表.首先,我们定义接口,以便我们的表可以接收提供的任何数据和列。

    import {
      ColumnDef,
      useReactTable,
      ...
    } from "@tanstack/react-table";
    
    interface ReactTableProps<TData> {
      data: TData[];
      columns: ColumnDef<TData>[];
    }
    
    const ReactTable = <TData extends object>({
      data,
      columns,
    }: ReactTableProps<TData>) => {
      const table = useReactTable({
        data,
        columns,
        getCoreRowModel: getCoreRowModel(),
      });
    
      return (
        ...
      )
    }
    

    然后,我们可以如下实现我们的表:

      return (
        <div className="App">
          <ReactTable data={orders} columns={orderColumns} />
          <ReactTable data={containers} columns={containerColumns} />
        </div>
      );
    
    

    如果你想更严格,你可以实现如下类型:

      return (
        <div className="App">
          <ReactTable<Orders> data={orders} columns={orderColumns} />
          <ReactTable<Container> data={containers} columns={containerColumns} />
        </div>
      );
    

    你可以在这里看到完整的代码:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-05
      • 1970-01-01
      • 1970-01-01
      • 2020-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多