|
| 1 | +```tsx |
| 2 | +import { Table, Transfer, TransferProps } from 'antd'; |
| 3 | +import { ColumnsType } from 'antd/lib/table'; |
| 4 | +import { TableRowSelection, TablePaginationConfig } from 'antd/lib/table/interface'; |
| 5 | +import difference from 'lodash/difference'; |
| 6 | +import React from 'react'; |
| 7 | + |
| 8 | +interface TableTransferProps<T> extends TransferProps<T> { |
| 9 | + leftColumns: ColumnsType<T>; |
| 10 | + leftPagination?: TablePaginationConfig; |
| 11 | + |
| 12 | + rightColumns: ColumnsType<T>; |
| 13 | + rightPagination?: TablePaginationConfig; |
| 14 | +} |
| 15 | + |
| 16 | +export function TableTransfer<T>({ |
| 17 | + leftColumns, |
| 18 | + rightColumns, |
| 19 | + leftPagination, |
| 20 | + rightPagination, |
| 21 | + ...restProps |
| 22 | +}: TableTransferProps<T>) { |
| 23 | + return ( |
| 24 | + <Transfer {...restProps}> |
| 25 | + {({ |
| 26 | + direction, |
| 27 | + filteredItems, |
| 28 | + onItemSelectAll, |
| 29 | + onItemSelect, |
| 30 | + selectedKeys: listSelectedKeys, |
| 31 | + disabled: listDisabled, |
| 32 | + }) => { |
| 33 | + const columns = direction === 'left' ? leftColumns : rightColumns; |
| 34 | + const pagination = direction === 'left' ? leftPagination : rightPagination; |
| 35 | + |
| 36 | + const rowSelection: TableRowSelection<any> = { |
| 37 | + getCheckboxProps: (item) => ({ disabled: listDisabled || item.disabled }), |
| 38 | + onSelectAll(selected, selectedRows) { |
| 39 | + const treeSelectedKeys = selectedRows |
| 40 | + .filter((item) => !item.disabled) |
| 41 | + .map(({ key }) => key); |
| 42 | + const diffKeys = selected |
| 43 | + ? difference(treeSelectedKeys, listSelectedKeys) |
| 44 | + : difference(listSelectedKeys, treeSelectedKeys); |
| 45 | + onItemSelectAll(diffKeys, selected); |
| 46 | + }, |
| 47 | + onSelect({ key }, selected) { |
| 48 | + onItemSelect(key, selected); |
| 49 | + }, |
| 50 | + selectedRowKeys: listSelectedKeys, |
| 51 | + }; |
| 52 | + |
| 53 | + return ( |
| 54 | + <Table |
| 55 | + rowSelection={rowSelection} |
| 56 | + columns={columns} |
| 57 | + dataSource={filteredItems} |
| 58 | + pagination={pagination} |
| 59 | + size="small" |
| 60 | + style={{ pointerEvents: listDisabled ? 'none' : null }} |
| 61 | + onRow={({ key, disabled: itemDisabled }) => ({ |
| 62 | + onClick: () => { |
| 63 | + if (itemDisabled || listDisabled) return; |
| 64 | + onItemSelect(key, !listSelectedKeys.includes(key)); |
| 65 | + }, |
| 66 | + })} |
| 67 | + /> |
| 68 | + ); |
| 69 | + }} |
| 70 | + </Transfer> |
| 71 | + ); |
| 72 | +} |
| 73 | +``` |
0 commit comments