react antd table 自动合并单元格


项目场景:

前端开发往往会遇到表格处理的问题,例如合并单元格,该文章给处理自动合并单元格的方法



问题:

例如我们想把下面的表格做出合并:

班级姓名班主任语文数学
高三(1)张三郝老师8989
高三(1)王五郝老师8989
高三(2)李四张老师8989
高三(2)小敏张老师8989
高三(1)小米郝老师8989

得到如下的表格样式:

班级姓名班主任语文数学
高三(1)张三郝老师8989
王五8989
高三(2)李四张老师8989
小敏8989
高三(1)小米郝老师8989


解决方案:

const data = [
  {
    class:'高三(1)',
    name:'张三',
    teacher:'郝老师',
    chinese:'89',
    mathematics:'89',
  },
  {
    class:'高三(1)',
    name:'王五',
    teacher:'郝老师',
    chinese:'89',
    mathematics:'89',
  },
  {
    class:'高三(2)',
    name:'李四',
    teacher:'张老师',
    chinese:'89',
    mathematics:'89',
  },
  {
    class:'高三(2)',
    name:'小敏',
    teacher:'张老师',
    chinese:'89',
    mathematics:'89',
  },
  {
    class:'高三(1)',
    name:'小米',
    teacher:'郝老师',
    chinese:'89',
    mathematics:'89',
  },
]

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',
    render: (text, record, index) => {
          const obj = {
            children: text !== null ? text : '',
            props: {}
          }
          obj.props.rowSpan = mergeCells(text, data,'teacher', index)//对班主任合并,则传班主任的字段作为key值

          return obj
     },
  },
  {
    title: '语文',
    dataIndex: 'chinese',
    key: 'chinese',
  },
  {
    title: '数学',
    dataIndex: 'mathematics',
    key: 'mathematics',
  },
];


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
}

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值