antd table合并行或者列(动态添加合并行、列)
表头只支持列合并,使用 column 里的 colSpan 进行设置。
表格支持行/列合并,使用 render 里的单元格属性 colSpan 或者 rowSpan 设值为 0 时,设置的表格不会渲染。
数据:
dataTableData = [
{
key: "0",
"category": "水果",
"name": "桃子",
"desc": "好吃"
}, {
key: "1",
"category": "水果",
"name": "茄子",
"desc": "好吃"
}, {
key: "3",
"category": "家禽",
"name": "牛肉",
"desc": "好吃"
}, {
key: "4",
"category": "家禽",
"name": "牛肉",
"desc": "好吃到停不下来"
}, {
key: "5",
"category": "家禽",
"name": "猪肉",
"desc": "吃不起,太贵"
}
]
列属性:
const columnsData = [
{
title: '分类',
dataIndex: 'category',
width:"30%",
render: (value, row, index) => {
const obj = {
children: value,
props: {},
};
obj.props.rowSpan = row.categoryrowSpan;
return obj;
}
},
{
title: '名称',
dataIndex: 'name',
width:"30%",
render: (value, row, index) => {
const obj = {
children: value,
props: {},
};
obj.props.rowSpan = row.namerowSpan;
return obj;
}
},
{
title: '评价',
dataIndex: 'desc',
render: (value, row, index) => {
const obj = {
children: value,
props: {},
};
obj.props.rowSpan = row.descrowSpan;
return obj;
}
},
];
对数据进行处理:
export const changeData = (data, field) => {
let count = 0;
let indexCount = 1;
while (indexCount < data.length) {
var item = data.slice(count, count + 1)[0];
if (!item[`${field}rowSpan`]) {
item[`${field}rowSpan`] = 1;
}
if (item[field] === data[indexCount][field]) {
item[`${field}rowSpan`]++;
data[indexCount][`${field}rowSpan`] = 0;
} else {
count = indexCount;
}
indexCount++;
}
return data
}
对data中的数据进行改造:
let propsList = ['category', 'name', 'desc']
propsList.map(item => {
dataTableData = changeData(dataTableData, item)
})
页面:
<Table columns={columnsData} dataSource={dataTableData} bordered />
参考: https://blog.csdn.net/weixin_44135121/article/details/108277720
|