621 字
3 分钟
基于 Antd Table 组件组件的二次封装,使其支持同列相同数据下的合并

背景#

最近在进行业务开发时,经常遇到同列相同数据下的合并,为了方便后续使用,我封装了一个基于 Antd Table 组件的二次封装,可以方便的实现同列相同数据下的合并

同列相同数据下的合并

实现思路#

Antd Table 组件的 Column 描述列描述对象中 onCell 属性可以用来设置单元格的样式,因此我们只需要在 onCell 属性中设置合并单元格 rowSpan 值即可。

简单介绍下 rowSpan 属性,rowSpan 属性用来设置单元格的跨行数,如果设置为 2,则表示单元格跨两行。 同时需要将被合并的单元格的 rowSpan 值设置为 0,来避免被合并的单元格被显示。

实现代码#

import { useMemo } from 'react'
import { Table, TableProps } from 'antd'
export default function SameGroupMergeTable(props: TableProps) {
const { columns, dataSource } = props;
const innerColumns = useMemo(() => {
if (!columns || !dataSource) return [];
return columns.map((column: any) => {
if (column.mergeColumn && !column.onCell) {
return {
...column,
onCell: (record: any, rowIndex: number | undefined) => {
const dataIndex = column.dataIndex;
const sameKey = dataSource.filter((item) => item[dataIndex] === record[dataIndex]);
if (sameKey.length === 1) {
return { rowSpan: 1 };
}
const sameKeyFirstIndex = dataSource.findIndex((item) => item[dataIndex] === record[dataIndex]);
if (rowIndex === sameKeyFirstIndex) {
return { rowSpan: sameKey.length };
}
return { rowSpan: 0 };
},
};
}
// 如果 column 中设置了 mergeColumn 和 onCell 属性,则需要重写 onCell 属性,因为可能需要用到 onCell 属性中的其他参数实现其他功能
if (column.mergeColumn && column.onCell) {
return {
...column,
// 重写 onCell, 给 onCell 传递一个参数,合并单元格的值(rowSpan)
onCell: (record: any, rowIndex: number | undefined) => {
const dataIndex = column.dataIndex;
const sameKey = dataSource.filter((item) => item[dataIndex] === record[dataIndex]);
if (sameKey.length === 1) {
return column.onCell(record, rowIndex, { rowSpan: 1 });
}
const sameKeyFirstIndex = dataSource.findIndex((item) => item[dataIndex] === record[dataIndex]);
if (rowIndex === sameKeyFirstIndex) {
return column.onCell(record, rowIndex, { rowSpan: sameKey.length });
}
return column.onCell(record, rowIndex, { rowSpan: 0 });
},
};
}
return column;
});
}, [columns, dataSource]);
return (
<Table {...props} columns={innerColumns} />
)
}

使用方式#

import SameGroupMergeTable from '@/src/components/SameGroupMergeTable';
const columns = [
{
title: 'Name',
dataIndex: 'name',
// 使用方式一:设置 mergeColumn 属性
mergeColumn: true,
},
{
title: 'Name',
dataIndex: 'name',
// 使用方式二:设置 mergeColumn 和 onCell 属性
mergeColumn: true,
onCell: (_record, rowIndex, mergeObject) => {
if (rowIndex === 0) {
return {
...mergeObject,
style: {
backgroundColor: "#E6F4FF",
}
}
}
return mergeObject;
},
},
];
const dataSource = [];
const Example = () => {
return <SameGroupMergeTable
columns={columns}
dataSource={dataSource}
/>;
};
export default Example;
TIP

通常情况下只需要设置 mergeColumn 属性即可

如果需要合并的列需要用到 onCell 属性中的其他参数实现其他功能,这通过 onCell 函数第三个形参 mergeObject 来实现。

基于 Antd Table 组件组件的二次封装,使其支持同列相同数据下的合并
https://www.mihouo.com/posts/front/a-wrapper-based-on-the-antd-table-component/
作者
发布于
2025-09-10
许可协议
CC BY-NC-SA 4.0