TableVirtuoso行props缺失'data-index'时仅显示一行数据
TableVirtuoso 仅显示一行数据问题排查
问题描述
照搬MUI官网的TableVirtuoso示例代码,仅修改了行组件、行内容渲染及表头渲染部分,但页面仅显示一行数据,相关代码如下:
const VirtuosoTableComponents: TableComponents<Data> = { Scroller: React.forwardRef<HTMLDivElement>((props, ref) => ( <TableContainer component={Paper} {...props} ref={ref} /> )), Table: (props) => ( <Table {...props} sx={{ borderCollapse: 'separate', tableLayout: 'fixed' }} /> ), TableHead, TableRow: ({ item: _item, 'data-index': index, ...props }) => <TableRow onClick={onRowClick(index)} {...props} />, TableBody: React.forwardRef<HTMLTableSectionElement>((props, ref) => ( <TableBody {...props} ref={ref} /> )), }; export default function ReactVirtualizedTable() { return ( <Paper style={{ height: 400, width: '100%' }}> <TableVirtuoso data={rows} components={VirtuosoTableComponents} fixedHeaderContent={fixedHeaderContent} itemContent={rowContent} /> </Paper> ); }
排查与解决方法
检查
rowContent渲染逻辑:itemContent传入的rowContent是行内容核心渲染函数,若未正确返回完整单元格结构,或行/单元格设置了height: 100%这类撑满容器的样式,会导致仅显示一行。需确保函数正确接收index和item参数,返回对应<TableCell>,且避免异常高度设置。示例:const rowContent = (index: number, item: Data) => ( <> <TableCell>{item.id}</TableCell> <TableCell>{item.name}</TableCell> {/* 其他对应列的单元格 */} </> );校验
fixedHeaderContent表头结构:表头的列数必须与rowContent渲染的列数完全匹配,且不要给表头设置过高固定高度,避免挤压表格主体空间。调整Table组件的
tableLayout属性:设置tableLayout: 'fixed'后,若未给列指定宽度,可能引发列宽异常。可给每个<TableCell>(含表头和内容行)设置明确宽度,或暂时移除该属性测试是否恢复正常。指定TableVirtuoso行高:TableVirtuoso默认自动计算行高,但若行内容高度不稳定,会导致虚拟滚动计算错误。手动指定
rowHeight属性,比如MUI TableRow默认高度56:<TableVirtuoso // 其他属性 rowHeight={56} />确认
rows数据有效性:通过console.log(rows.length)验证数据数组是否包含多条数据,而非仅一条。
内容的提问来源于stack exchange,提问作者Deuxis
相关产品推荐
相关产品推荐

