ant design-Table组件实现每一行某个特定字段连续相同进行行合并。
Posted 木易锅巴
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ant design-Table组件实现每一行某个特定字段连续相同进行行合并。相关的知识,希望对你有一定的参考价值。
需求:表格数据,要求后台返回的数据中,每一行客户姓名连续相同时进行行合并。
需求原型:
解决方案:
首先看ant Table官网的demo,如何实现行合并:
import { Table } from \'antd\'; // In the fifth row, other columns are merged into first column // by setting it\'s colSpan to be 0 const renderContent = (value, row, index) => { const obj = { children: value, props: {}, }; if (index === 4) { obj.props.colSpan = 0; } return obj; }; const columns = [ { title: \'Name\', dataIndex: \'name\', render: (text, row, index) => { if (index < 4) { return <a>{text}</a>; } return { children: <a>{text}</a>, props: { colSpan: 5, }, }; }, }, { title: \'Age\', dataIndex: \'age\', render: renderContent, }, { title: \'Home phone\', colSpan: 2, dataIndex: \'tel\', render: (value, row, index) => { const obj = { children: value, props: {}, }; if (index === 2) { obj.props.rowSpan = 2; } // These two are merged into above cell if (index === 3) { obj.props.rowSpan = 0; } if (index === 4) { obj.props.colSpan = 0; } return obj; }, }, { title: \'Phone\', colSpan: 0, dataIndex: \'phone\', render: renderContent, }, { title: \'Address\', dataIndex: \'address\', render: renderContent, }, ]; const data = [ { key: \'1\', name: \'John Brown\', age: 32, tel: \'0571-22098909\', phone: 18889898989, address: \'New York No. 1 Lake Park\', }, { key: \'2\', name: \'Jim Green\', tel: \'0571-22098333\', phone: 18889898888, age: 42, address: \'London No. 1 Lake Park\', }, { key: \'3\', name: \'Joe Black\', age: 32, tel: \'0575-22098909\', phone: 18900010002, address: \'Sidney No. 1 Lake Park\', }, { key: \'4\', name: \'Jim Red\', age: 18, tel: \'0575-22098909\', phone: 18900010002, address: \'London No. 2 Lake Park\', }, { key: \'5\', name: \'Jake White\', age: 18, tel: \'0575-22098909\', phone: 18900010002, address: \'Dublin No. 2 Lake Park\', }, ]; ReactDOM.render(<Table columns={columns} dataSource={data} bordered />, mountNode);
demo核心代码:
如上图所示,demo中哪一行进行行合并是固定写死的,那如何实现后台数据客户姓名字段连续相同时合并呢。
代码如下:
/** * @param {*} data [后台数据] * @param {*} key [要合并的字段] * @param {*} target [后台数据对应的index] * @returns 合并的行数 * method of 获取合并的行数 */ function getRowSpanCount(data, key, target) { if (!Array.isArray(data)) return 1; data = data.map(_ => _[key]); // 只取出筛选项 let preValue = data[0]; const res = [[preValue]]; // 放进二维数组里 let index = 0; // 二维数组下标 for (let i = 1; i < data.length; i++) { if (data[i] === preValue) { // 相同放进二维数组 res[index].push(data[i]); } else { // 不相同二维数组下标后移 index += 1; res[index] = []; res[index].push(data[i]); preValue = data[i]; } } const arr = []; res.forEach((_) => { const len = _.length; for (let i = 0; i < len; i++) { arr.push(i === 0 ? len : 0); } }); return arr[target]; }
如何调用:
页面效果:
以上是关于ant design-Table组件实现每一行某个特定字段连续相同进行行合并。的主要内容,如果未能解决你的问题,请参考以下文章
带你封装一个上传图片组件(ant design+react)