|
| 1 | +import React, { useState } from 'react'; |
| 2 | +import type { ColumnType } from 'rc-table'; |
| 3 | +import Table from 'rc-table'; |
| 4 | +import '../../assets/index.less'; |
| 5 | + |
| 6 | +// 合并单元格 |
| 7 | +export const getRowSpan = (source: (string | number | undefined)[] = []) => { |
| 8 | + const list: { rowSpan?: number }[] = []; |
| 9 | + let span = 0; |
| 10 | + source.reverse().forEach((key, index) => { |
| 11 | + span = span + 1; |
| 12 | + if (key !== source[index + 1]) { |
| 13 | + list.push({ rowSpan: span }); |
| 14 | + span = 0; |
| 15 | + } else { |
| 16 | + list.push({ rowSpan: 0 }); |
| 17 | + } |
| 18 | + }); |
| 19 | + return list.reverse(); |
| 20 | +}; |
| 21 | + |
| 22 | +const Demo = () => { |
| 23 | + const [expandedRowKeys, setExpandedRowKeys] = useState<readonly React.Key[]>([]); |
| 24 | + |
| 25 | + const data = [ |
| 26 | + { key: 'a', a: '小二', d: '文零西路' }, |
| 27 | + { key: 'b', a: '张三', d: '文一西路' }, |
| 28 | + { key: 'c', a: '张三', d: '文二西路' }, |
| 29 | + ]; |
| 30 | + const rowKeys = data.map(item => item.key); |
| 31 | + |
| 32 | + const rowSpanList = getRowSpan(data.map(item => item.a)); |
| 33 | + |
| 34 | + const columns: ColumnType<Record<string, any>>[] = [ |
| 35 | + { |
| 36 | + title: '手机号', |
| 37 | + dataIndex: 'a', |
| 38 | + width: 100, |
| 39 | + fixed: 'left', |
| 40 | + onCell: (_, index) => { |
| 41 | + const { rowSpan = 1 } = rowSpanList[index]; |
| 42 | + const props: React.TdHTMLAttributes<HTMLTableCellElement> = {}; |
| 43 | + props.rowSpan = rowSpan; |
| 44 | + if (rowSpan >= 1) { |
| 45 | + let currentRowSpan = rowSpan; |
| 46 | + for (let i = index; i < index + rowSpan; i += 1) { |
| 47 | + const rowKey = rowKeys[i]; |
| 48 | + if (expandedRowKeys.includes(rowKey)) { |
| 49 | + currentRowSpan += 1; |
| 50 | + } |
| 51 | + } |
| 52 | + props.rowSpan = currentRowSpan; |
| 53 | + } |
| 54 | + return props; |
| 55 | + }, |
| 56 | + }, |
| 57 | + Table.EXPAND_COLUMN, |
| 58 | + { title: 'Address', fixed: 'right', dataIndex: 'd', width: 200 }, |
| 59 | + ]; |
| 60 | + |
| 61 | + return ( |
| 62 | + <div style={{ height: 10000 }}> |
| 63 | + <h2>expanded & sticky</h2> |
| 64 | + <Table<Record<string, any>> |
| 65 | + rowKey="key" |
| 66 | + sticky |
| 67 | + scroll={{ x: 800 }} |
| 68 | + columns={columns} |
| 69 | + data={data} |
| 70 | + expandable={{ |
| 71 | + expandedRowOffset: 1, |
| 72 | + expandedRowKeys, |
| 73 | + onExpandedRowsChange: keys => setExpandedRowKeys(keys), |
| 74 | + expandedRowRender: record => <p style={{ margin: 0 }}>{record.key}</p>, |
| 75 | + }} |
| 76 | + className="table" |
| 77 | + /> |
| 78 | + </div> |
| 79 | + ); |
| 80 | +}; |
| 81 | + |
| 82 | +export default Demo; |
0 commit comments