You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.01 17:05:25