reactjs 类型T类型脚本上不存在属性ID

bjg7j2ky  于 2023-03-01  发布在  React
关注(0)|答案(1)|浏览(126)

为什么会出现此错误,如何修复?

Property 'id' does not exist on type 'T'.

价格为row.original.id

export interface ITable<T> {
  columns: any;
  data: T[];
  with_transition?: boolean;
  onClick?: (price_id: string) => void;
}

export default function Table<T extends object>({
  columns,
  data,
  with_transition,
  onClick
}: ITable<T>) {
  const {
    getTableProps, // table props from react-table
    getTableBodyProps, // table body props from react-table
    headerGroups, // headerGroups, if your table has groupings
    rows, // rows for the table based on the data passed
    prepareRow // Prepare the row (this function needs to be called for each row before getting the row props)
  } = useTable({
    columns,
    data
  });
  return (
    <table {...getTableProps()}>
      <thead>
        {headerGroups.map(headerGroup => (
          <tr {...headerGroup.getHeaderGroupProps()}>
            {headerGroup.headers.map(column => (
              <th {...column.getHeaderProps()}>{column.render("Header")}</th>
            ))}
          </tr>
        ))}
      </thead>
      <tbody className={`${with_transition && 't-body-transition'}`} {...getTableBodyProps()}>
        {rows.map((row, i) => {
          prepareRow(row);
          return (
            <tr className="transition" {...row.getRowProps()}>
              {row.cells.map(cell => {
                return <td onClick={() => onClick && row.original.id && cell.column.Header !== 'Button' && onClick(row.original.id)} className="transition" {...cell.getCellProps()}>{cell.render("Cell")}</td>;
              })}
            </tr>
          );
        })}
      </tbody>
    </table>
  )
}

有谁能解决这个问题吗?我想使用泛型而不是静态类型。

6kkfgxo0

6kkfgxo01#

您可以将泛型类型约束为{ id: string },或者使用另一种方法将onRowClick函数动态化。

export interface ITable<T> {
  ...,
  onRowClick?: [keyof T, (value: T[keyof T]) => void];
}

function Table<T>({
  ...,
  onRowClick
}: ITable<T>) {
  return (
    ...,
     <tr className="transition" {...row.getRowProps()}>
       {row.cells.map(cell => (
         <td  
            onClick={() => {
              if (onRowClick) {
                const [key, onClick] = onRowClick;

                onClick(row.original[key]);
              }
            }}>
            ...
          </td>
        ))}
     </tr>
  )
}

通过传递您的键和onClick函数来使用它。

<Table 
  ...
  onRowClick={['price_id', yourRowClickFunction]}
/>

相关问题