假如你有这样的一个数据:
[
{
"bigClass":"吃的",
"smallClass":"水果",
"item":"苹果"
},
{
"bigClass":"吃的",
"smallClass":"水果",
"item":"香蕉"
},
{
"bigClass":"吃的",
"smallClass":"面食",
"item":"刀削面"
},
{
"bigClass":"吃的",
"smallClass":"面食",
"item":"拉面"
},
{
"bigClass":"喝的",
"smallClass":"碳酸饮料",
"item":"可乐"
},
{
"bigClass":"坐的",
"smallClass":"车",
"item":"奥迪"
},
{
"bigClass":"坐的",
"smallClass":"车",
"item":"奔驰"
},
{
"bigClass":"用的",
"smallClass":"工作用的",
"item":"电脑"
}
]
需求如下:
代码实现:文章来源:https://www.toymoban.com/news/detail-838092.html
const columns: any = [
{
title: '业务方向',
dataIndex: 'bigClass',
key: 'bigClass',
onCell: (record: any) => {
// 新增一个lineRowSpan记录该合并的行数
return {rowSpan: record.lineRowSpan};
}
},
{
title: '子业务',
dataIndex: 'smallClass',
key: 'smallClass',
onCell: (record: any) => {
// 新增一个subLineRowSpan记录该合并的行数
return {rowSpan: record.subLineRowSpan};
}
},
{
title: '功能模块',
dataIndex: 'item',
key: 'item'
}
];
// 处理数据的函数,主要是加上行数的属性
const handleDataSource = (data: any[]) => {
const lineCounts: any = {};
data.forEach((obj) => {
const bigClass = obj.bigClass;
const smallClass = obj.smallClass;
lineCounts[bigClass] = (lineCounts[bigClass] || 0) + 1;
lineCounts[smallClass] = (lineCounts[smallClass] || 0) + 1;
const a = data.filter(o => o.bigClass === bigClass).length;
const b = data.filter(o => o.smallClass === smallClass).length;
obj.lineRowSpan = lineCounts[bigClass] === 1 ? a : 0;
obj.subLineRowSpan = lineCounts[smallClass] === 1 ? b : 0;
});
return data;
};
// 展开函数处理
const handleExpand = (expanded: boolean, record: any) => {
if (record.funcModule === expandedRowKey) {
setExpandedRowKey('');
} else {
setExpandedRowKey(record.item);
getExpandData(getFuncModuleCode(record.item), startDate, endDate);
}
//展开时,对原始数据进行修改
expanded && setServiceData(handleExpandDataSource(record.item));
//不展开,使用原始数据进行渲染即可
!expanded && setServiceData(initData);
};
// 举例
const handleExpandDataSource = (item: string) => {
let newArr: any = [];
if (item === '苹果' || item === '香蕉') {
newArr = initData?.map((item) => {
if (item.item === '苹果') {
return {
...item,
lineRowSpan: 5,
subLineRowSpan: 3
};
} else {
return item;
}
});
}
return newArr;
};
文章来源地址https://www.toymoban.com/news/detail-838092.html
到了这里,关于react + antdesign table组件合并行,展开子表格的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!