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

React MUI表格中实现一行内双数据行并对齐的问题咨询

React MUI表格中实现一行内多组数据行对齐的问题咨询

我完全理解你的需求——你想把sections数组里三组各20行的数据,按对应行的位置放在表格的同一行中展示,而不是现在这样先显示完第一组所有行、再显示第二组和第三组,导致各行无法对齐的情况。

先帮你分析下当前代码的问题:你现在是循环遍历每个section,然后为每个section里的每一行生成一个TableRow,在这个行里又三次遍历headers,只渲染当前section(index=0/1/2)的内容,其他两组的单元格都是空值。这就导致第一组的20行会先全部渲染出来(每行后面跟着空的第二、三组单元格),接着是第二组的20行(前面是空的第一组单元格),最后是第三组的20行,自然没法实现你想要的对齐效果。

要解决这个问题,我们应该按行索引来循环,而不是循环sections。因为三组数据的行数一致(都是20行),我们可以取其中一组的长度作为循环次数,然后在每个TableRow里,依次渲染三组对应行的所有列:

{sections[0].map((_, rowIndex) => (
  <TableRow
    key={rowIndex}
    sx={{
      '&:nth-of-type(odd)': {
        backgroundColor: 'zebra.odd',
      },
      color: 'primary.main',
    }}
  >
    {/* 渲染第一组数据的所有列 */}
    {headers.map((header, i) => (
      <TableCell
        key={`group0-${i}`}
        component='th'
        scope='col'
        align='left'
        sx={tableCellStyles}
      >
        <Typography
          sx={{
            color: 'primary.main',
            fontWeight: 400,
            fontSize: 14,
          }}
        >
          {sections[0][rowIndex][header.toLowerCase()] ?? ''}
        </Typography>
      </TableCell>
    ))}
    {/* 渲染第二组数据的所有列 */}
    {headers.map((header, i) => (
      <TableCell
        key={`group1-${i}`}
        component='th'
        scope='row'
        align='left'
        sx={tableCellStyles}
      >
        <Typography
          sx={{
            color: 'primary.main',
            fontWeight: 400,
            fontSize: 14,
          }}
        >
          {sections[1][rowIndex][header.toLowerCase()] ?? ''}
        </Typography>
      </TableCell>
    ))}
    {/* 渲染第三组数据的所有列 */}
    {headers.map((header, i) => (
      <TableCell
        key={`group2-${i}`}
        component='th'
        scope='col'
        align='left'
        sx={tableCellStyles}
      >
        <Typography
          sx={{
            color: 'primary.main',
            fontWeight: 400,
            fontSize: 14,
          }}
        >
          {sections[2][rowIndex][header.toLowerCase()] ?? ''}
        </Typography>
      </TableCell>
    ))}
  </TableRow>
))}

修改后,每个TableRow会同时展示三组数据中对应索引行的内容:比如第1行显示sections[0][0]、sections[1][0]、sections[2][0]的所有列,第2行显示sections[0][1]、sections[1][1]、sections[2][1]的所有列,以此类推,就能实现你想要的对齐效果了。

另外,为了避免某组数据行数不一致导致的数组越界问题,你可以先做一个长度校验,取三组中最小的行数来循环:

const maxRowCount = Math.min(...sections.map(sec => sec.length));

{Array.from({length: maxRowCount}).map((_, rowIndex) => (
  // 上述TableRow代码
))}

备注:内容来源于stack exchange,提问作者Karan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 08:54:32