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

如何使用Material-UI实现带合并单元格的分组表格(附示例数据)

实现分组合并单元格的Material-UI表格

步骤1:数据分组处理

先把原始API数据按lo.value字段分组,将同一位置的kind归类到一起:

const data = [
  {"id":"1", "lo":{"code":101,"value":"right","pcode":10}, "kind":"a"},
  {"id":"2", "lo":{"code":101,"value":"right","pcode":10}, "kind":"b"},
  {"id":"3", "lo":{"code":101,"value":"right","pcode":10}, "kind":"c"},
  {"id":"4", "lo":{"code":102,"value":"left","pcode":10}, "kind":"d"},
  {"id":"5", "lo":{"code":102,"value":"left","pcode":10}, "kind":"e"},
  {"id":"6", "lo":{"code":103,"value":"center","pcode":10}, "kind":"f"},
  {"id":"7", "lo":{"code":103,"value":"center","pcode":10}, "kind":"g"},
  {"id":"8", "lo":{"code":103,"value":"center","pcode":10}, "kind":"h"},
  {"id":"9", "lo":{"code":104,"value":"bottom","pcode":10}, "kind":"i"},
];

// 按位置分组
const groupedData = data.reduce((acc, item) => {
  const position = item.lo.value;
  if (!acc[position]) acc[position] = [];
  acc[position].push(item.kind);
  return acc;
}, {});

// 转换为渲染用的数组格式
const tableData = Object.entries(groupedData).map(([position, kinds]) => ({ position, kinds }));

步骤2:编写Material-UI表格组件

利用TableRow和TableCell的rowSpan属性实现单元格合并,生成符合示例样式的表格:

import React from 'react';
import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper } from '@mui/material';

const GroupedTable = () => {
  return (
    <TableContainer component={Paper}>
      <Table sx={{ minWidth: 650 }} aria-label="分组表格">
        <TableHead>
          <TableRow>
            <TableCell>位置</TableCell>
            <TableCell>类型</TableCell>
          </TableRow>
        </TableHead>
        <TableBody>
          {tableData.map((group) =>
            group.kinds.map((kind, idx) => (
              <TableRow key={`${group.position}-${idx}`}>
                {/* 仅分组第一行渲染位置单元格,并设置合并行数 */}
                {idx === 0 && (
                  <TableCell rowSpan={group.kinds.length} align="center">
                    {group.position}
                  </TableCell>
                )}
                <TableCell align="center">{kind}</TableCell>
              </TableRow>
            ))
          )}
        </TableBody>
      </Table>
    </TableContainer>
  );
};

export default GroupedTable;

使用说明

  1. 先安装Material-UI依赖:
npm install @mui/material @emotion/react @emotion/styled
  1. 在项目中引入GroupedTable组件即可使用。

内容的提问来源于stack exchange,提问作者kwon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 15:55:20