继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

react antd Table动态合并单元格

dear_B_Q
关注TA
已关注
手记 1
粉丝 1
获赞 1

@[TOC](antd Table合并单元格)

示例数据

原始数组

const data = [
  {
    key: '0',
    name: 'John Brown',
    age:22,
    address: 'New York No. 1 Lake Park',
    tags: ['nice', 'developer'],
  },
  {
    key: '1',
    name: 'John Brown',
    age: 42,
    address: 'London No. 1 Lake Park',
    tags: ['loser'],
  },
  {
    key: '2',
    name: 'John Brown',
    age:22,
    address: 'New York No. 1 Lake Park',
    tags: ['nice', 'developer'],
  },
  {
    key: '5',
    name: 'Joe Black',
    age: 3,
    address: 'Sidney No. 1 Lake Park',
    tags: ['cool', 'teacher'],
  },
  {
    key: '6',
    name: 'Joe Black',
    age: 342,
    address: 'Sidney No. 1 Lake Park',
    tags: ['cool', 'teacher'],
  },
  {
    key: '7',
    name: 'Joe Black',
    age: 62,
    address: 'Sidney No. 1 Lake Park',
    tags: ['cool', 'teacher'],
  },
];

原始数据 使用Table展示如下

在这里插入图片描述

name是本文实例需要合并的字段

数据字段包括key``name``age``address``tags等假数据,目的是实现将具有相同name的元素合并为一个数组,然后将这些数组展开成为符合antd Table渲染条件的新数组,如下:

在这里插入图片描述

合并结果如下

在这里插入图片描述

合并单元格解决方案

合并函数

//合并数组单元格
  createNewArr=(data)=>{
    return data.reduce((result, item) => {
    //首先将name字段作为新数组result取出
        if (result.indexOf(item.name) < 0) {
            result.push(item.name)
        }
        return result
    }, []).reduce((result, name) => {
    //将name相同的数据作为新数组取出,并在其内部添加新字段**rowSpan**
      const children = data.filter(item => item.name === name);
      result = result.concat(
        children.map((item, index) => ({
          ...item,
          rowSpan: index === 0 ? children.length : 0,//将第一行数据添加rowSpan字段
        }))
      )
      return result;
    }, [])
  }

使用方法

const columns = [
     {
       title: '分类名称',
       dataIndex: 'name',
       key: 'name',
       render(_, row) {
           return {
             children: row.name,
             props: {
               rowSpan: row.rowSpan,
             }
           }
         }
     },
]

//Table传入数据之前对数据做处理
<Table columns={columns} dataSource={this.createNewArr(data)}/>
作者:黄仕达

编辑人:苑百琦
Ps:引用请标明出处,感谢!

本文由博客一文多发平台 OpenWrite 发布!

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP