首页 > 解决方案 > Typescript Material-UI Table重复代码问题

问题描述

抱歉,问题标题如此模糊,想不出更好的办法。

我试图弄清楚Material-UI 表格的 Typescript 实现,特别是“排序和选择”下的表格。它方便地有一个沙盒演示

所以我有多个带有表格的页面。如果我只是按原样复制粘贴此代码(当然还有数据和样式调整),则会发生很多重复的代码。我已经设法解决了大部分问题,但我在EnhancedTablePropsEnhancedTableHead.

我无法做到这一点,因为他们使用Data接口,每个表都不同。所以数据必须为每个表保留,不能统一。

我想不出一个合适的解决方案,主要是因为我对 Typescript 很陌生。

interface EnhancedTableProps {
  classes: ReturnType<typeof useStyles>;
  numSelected: number;
  onRequestSort: (event: React.MouseEvent<unknown>, property: keyof Data) => void;
  onSelectAllClick: (event: React.ChangeEvent<HTMLInputElement>) => void;
  order: Order;
  orderBy: string;
  rowCount: number;
}

function EnhancedTableHead(props: EnhancedTableProps) {
  const { classes, onSelectAllClick, order, orderBy, numSelected, rowCount, onRequestSort } = props;
  const createSortHandler = (property: keyof Data) => (event: React.MouseEvent<unknown>) => {
    onRequestSort(event, property);
  };

  return (
    <TableHead>
      <TableRow>
        <TableCell padding="checkbox">
          <Checkbox
            indeterminate={numSelected > 0 && numSelected < rowCount}
            checked={rowCount > 0 && numSelected === rowCount}
            onChange={onSelectAllClick}
            inputProps={{ 'aria-label': 'select all desserts' }}
          />
        </TableCell>
        {headCells.map((headCell) => (
          <TableCell
            key={headCell.id}
            align={headCell.numeric ? 'right' : 'left'}
            padding={headCell.disablePadding ? 'none' : 'normal'}
            sortDirection={orderBy === headCell.id ? order : false}
          >
            <TableSortLabel
              active={orderBy === headCell.id}
              direction={orderBy === headCell.id ? order : 'asc'}
              onClick={createSortHandler(headCell.id)}
            >
              {headCell.label}
              {orderBy === headCell.id ? (
                <span className={classes.visuallyHidden}>
                  {order === 'desc' ? 'sorted descending' : 'sorted ascending'}
                </span>
              ) : null}
            </TableSortLabel>
          </TableCell>
        ))}
      </TableRow>
    </TableHead>
  );
}

标签: javascripttypescriptmaterial-ui

解决方案


使Data通用

https://react-typescript-cheatsheet.netlify.app/docs/advanced/patterns_by_usecase/#generic-components

interface EnhancedTableProps<Data> {
  // ...
  onRequestSort: (event: React.MouseEvent<unknown>, property: keyof Data) => void;
}

function EnhancedTableHead<Data>(props: EnhancedTableProps<Data>) {
  // ...
}

推荐阅读