1. 首先要對后台返回的表格數據排序,把需要合並的相同的字段排在一起。這一步一般后台會處理好。
2. 在表格組件中創建一個temp對象,用來存放已經合並的字段。
3. 新建一個方法mergecells,在方法遍歷數據,相同的字段累計加1,遍歷之后返回重復次數。
4. 在表格的columns數據中使用mergecells方法,詳情看下列代碼。
1 import React, { Component } from 'react' 2 import { Table, Icon } from 'antd' 3 import pagination from 'src/components/pagination' 4 5 class TableList extends Component { 6 7 render () { 8 const temp = {} // 當前重復的值,支持多列 9 /** 10 * 動態合並表格方法 11 * @param {*} text 表格每列對應的值 12 * @param {*} data 后台返回的展示數據數組, 數據需要按字段排序 13 * @param {*} columns 表格每列表頭字段 14 */ 15 const mergeCells = (text, data, columns) => { 16 let i = 0 17 if (text !== temp[columns]){ 18 temp[columns] = text 19 data.forEach(((item) => { 20 if (item[columns] === temp[columns]){ 21 i += 1 22 } 23 })) 24 } 25 return i 26 } 27 const renderContent = (value, row, index) => { 28 const obj = { 29 children: value, 30 props: {}, 31 } 32 return obj 33 } 34 const columns = [ 35 { 36 title: '序號', 37 dataIndex: 'serialNumber', 38 render: renderContent, 39 }, 40 { 41 title: '渠道一', 42 dataIndex: 'firstClassBrand', 43 render: (value, row, index) => { 44 const obj = { 45 children: value, 46 props: {}, 47 } 48 obj.props.rowSpan = mergeCells(row.firstClassBrand, this.props.data, 'firstClassBrand') 49 return obj 50 }, 51 }, 52 { 53 title: '渠道二', 54 dataIndex: 'twoTierBrand', 55 render: (value, row, index) => { 56 const obj = { 57 children: value, 58 props: {} 59 } 60 obj.props.rowSpan = mergeCells(row.twoTierBrand, this.props.data, 'twoTierBrand') 61 return obj 62 }, 63 } 64 ] 65 return( 66 <Table columns={columns} dataSource={this.props.data} pagination={pagination({ total: 100 })} bordered /> 67 ) 68 } 69 } 70 71 export default TableList