react 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 發布!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM