Ant Design Table表格动态合并

import React from "react";
import {Table} from 'antd'

const Demo = () => {
    const mergeCells = (text, data, key, index) => {
        // 上一行该列数据是否一样
        if (index !== 0 && text === data[index - 1][key]) {
            return 0;
        }
        let rowSpan = 1;
        // 判断下一行是否相等
        for (let i = index + 1; i < data.length; i++) {
            if (text !== data[i][key]) {
                break;
            }
            rowSpan++;
        }
        return rowSpan;
    };
 
 
    const columns  = [
        {
            title: '班级',
            dataIndex: 'class',
            key: 'class',
            render: (text, record, index) => {
                const obj = {
                    children: text !== null ? text : '',
                    props: {},
                };
                obj.props.rowSpan = mergeCells(text, data, 'class', index);// 对班级合并,则传班级的字段作为key值
                return obj;
            },
        },
        {
            title: '姓名',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: '班主任',
            dataIndex: 'teacher',
            key: 'teacher',
        },
        {
            title: '语文',
            dataIndex: 'chinese',
            key: 'chinese',
        },
        {
            title: '数学',
            dataIndex: 'mathematics',
            key: 'mathematics',
        },
    ];
 
 
    const data = [
        {
            key: 1,
            class: '高三(1)',
            name: '张三',
            teacher: '郝老师',
            chinese: '89',
            mathematics: '89',
        },
        {
            key: 2,
            class: '高三(1)',
            name: '王五',
            teacher: '郝老师',
            chinese: '89',
            mathematics: '89',
        },
        {
            key: 3,
            class: '高三(2)',
            name: '李四',
            teacher: '张老师',
            chinese: '89',
            mathematics: '89',
        },
        {
            key: 4,
            class: '高三(2)',
            name: '小敏',
            teacher: '张老师',
            chinese: '89',
            mathematics: '89',
        },
        {
            key: 5,
            class: '高三(1)',
            name: '小米',
            teacher: '郝老师',
            chinese: '89',
            mathematics: '89',
        },
    ];
 
 
    return (
        <div>
            <Table dataSource={data} columns={columns} />
        </div>
    );

};

export default Demo;

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值