效果展示
代码
table内容
<Table {...tableProps} />
tableProps结构
const tableProps: any = {
columns,
dataSource,
// 下面的不重要
pagination: {
current: pageNo,
total,
showTotal: (total: number) => `共 ${total} 条`,
onChange: (page: number, size: number) => this.getList(page, size),
showSizeChanger: true,
pageSizeOptions: ["5", "10", "20", "30", "50"],
onShowSizeChange: (page: number, size: number) => this.getList(page, size),
},
onChange: this.onChange,
}
columns数据 合并方法的应用
const columns: ColumnProps<any>[] = [
{
title: "Name",
dataIndex: 'name',
},
{
title: "Age",
dataIndex: 'age',
},
{
title: "状态",
dataIndex: 'status',
render: (text, data, index) => {
return this.mergeRender(text, data, index)
}
},
]
测试数据dataSource
dataSource: [
{
name: '崔连长',
age: 38,
status: '离职',
},
{
name: '张三',
age: 36,
status: '离职',
},
{
name: '齐大白话',
age: 39,
status: '在职',
},
{
name: '李四',
age: 30,
status: '在职',
},
{
name: '小红',
age: 28,
status: '离职',
},
],
mergeRender方法
mergeRender = (text: any, record: any, index: number) => {
let obj = {
children: text,
props: {
rowSpan: 0
},
};
obj.props.rowSpan = this.getRowSpanCount(this.state.dataSource, 'status', index)
return obj;
}
getRowSpanCount单元格合并(核心)
/**
* @param {*} data [后台数据]
* @param {*} key [要合并的字段]
* @param {*} target [后台数据对应的index]
* @returns 合并的行数
* method of 获取合并的行数
*/
getRowSpanCount = (data: any, key: any, target: any) => {
if (!Array.isArray(data)) return 1;
data = data.map(_ => _[key]); // 只取出筛选项
let preValue = data[0];
const res = [[preValue]]; // 放进二维数组里
let index = 0; // 二维数组下标
for (let i = 1; i < data.length; i++) {
if (data[i] === preValue) { // 相同放进二维数组
res[index].push(data[i]);
} else { // 不相同二维数组下标后移
index += 1;
res[index] = [];
res[index].push(data[i]);
preValue = data[i];
}
}
const arr: any = [];
res.forEach((_) => {
const len = _.length;
for (let i = 0; i < len; i++) {
arr.push(i === 0 ? len : 0);
}
});
return arr[target];
}
其他方法(不重要)
getList = (pageNo: number, pageSize: number) => {
let {total, dataSource} = this.state
this.setState({ loading: true })
setTimeout(() => {
this.setState({ loading: false })
total++
dataSource.push({
name: '李四',
age: '30',
status: '在职',
},)
this.setState({ pageNo, total: total, dataSource: dataSource, pageSize });
}, 1000)
}
onChange = (pagination: any, filters: any, sorter: any) => {
const { order = "ascend", columnKey = "age" } = sorter;
const { orderObj, dataSource } = this.state;
const orderBy = order === "ascend" ? "asc" : "desc";
if (orderObj.name !== columnKey || orderObj.orderBy !== orderBy) {
let newData = []
if(orderBy === 'desc') {
newData = dataSource.sort((a: any, b: any) => a.age - b.age)
} else {
newData = dataSource.sort((a: any, b: any) => b.age - a.age)
}
console.log(newData, dataSource, orderBy)
this.setState({
pageNo: 1,
orderObj: {
orderBy,
name: columnKey,
dataSource: newData,
},
});
}
}
getRowSpanCount方法是本文的核心方法,只需灵活应用即可达到想要的效果