javascript - Typescript Material-UI Table重复代码问题
问题描述
抱歉,问题标题如此模糊,想不出更好的办法。
我试图弄清楚Material-UI 表格的 Typescript 实现,特别是“排序和选择”下的表格。它方便地有一个沙盒演示。
所以我有多个带有表格的页面。如果我只是按原样复制粘贴此代码(当然还有数据和样式调整),则会发生很多重复的代码。我已经设法解决了大部分问题,但我在EnhancedTableProps
和EnhancedTableHead
.
我无法做到这一点,因为他们使用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>
);
}
解决方案
使Data
通用
interface EnhancedTableProps<Data> {
// ...
onRequestSort: (event: React.MouseEvent<unknown>, property: keyof Data) => void;
}
function EnhancedTableHead<Data>(props: EnhancedTableProps<Data>) {
// ...
}
推荐阅读
- r - R中的for循环错误我找不到
- python - 对象的属性存储在同一个内存地址
- python - 初始化函数时的tensorboard ModuleNotFoundError
- sonarqube - 如何查看每个测试的代码覆盖率?
- android - MutableLiveData
to MutableLiveData - c - 为什么函数没有将输入映射到我的变量?
- bash - 在终端中使用 crontab 重新启动后继续执行脚本
- vba - 将文本添加到电子邮件线程
- python - Pandas Multindex:迭代行并添加特定值以创建新变量
- amazon-web-services - AWS:FileNotFoundError:[Errno 2] 没有这样的文件或目录