import React, { useState, useRef, useEffect, useMemo } from 'react'; import { Table } from 'antd'; import { TableProps } from 'antd/es/table'; import { VariableSizeGrid } from 'react-window'; import { combine } from 'common'; import styles from './style.module.less'; export type TVirtualTableProps = TableProps & { tableWidth?: number; }; /** * 虚拟滚动表格 */ export const VirtualTable = combine(({ stores, tableWidth = 0, columns = [], ...props }) => { const { componentSize = 'large' } = stores.layout.setting; const gridRef = useRef(null); const { x = 0, y = 0 } = props.scroll || {}; useEffect(() => { gridRef.current?.resetAfterIndices({ rowIndex: 0, columnIndex: 0, shouldForceUpdate: false, }); }, [tableWidth]); // 给剩余的列分配宽度,并过滤 fixed const mergedColumns = useMemo(() => { let laveWidth = +x; const { length } = columns.filter(({ width }) => { if (width) laveWidth -= +width; return !width; }); const width = Math.floor(laveWidth / length); let mergedColumns = columns.map(({ fixed, ...column }) => (column.width ? column : { ...column, width })); // 实际宽度大于滚动宽度时,放大列宽 if (tableWidth > x) { const scale = tableWidth / +x; mergedColumns = mergedColumns.map(({ width, ...column }) => { return { ...column, width: Math.floor(+width! * scale) }; }); } return mergedColumns; }, [x, tableWidth]); const [connectObject] = useState(() => { const obj = {}; Object.defineProperty(obj, 'scrollLeft', { get: () => null, set: (scrollLeft) => { if (gridRef.current) { gridRef.current!.scrollTo({ scrollLeft, } as any); } }, }); return obj; }); const renderVirtualList = (rawData: any, { ref, onScroll }: any) => { ref.current = connectObject; return ( rowHeights[componentSize]} width={tableWidth} onScroll={({ scrollLeft }) => onScroll({ scrollLeft })} columnWidth={(index) => +mergedColumns[index].width!} > {({ columnIndex, rowIndex, style }) => { const { dataIndex, render } = mergedColumns[columnIndex] as any; const data = rawData[rowIndex]; const column = data['' + dataIndex]; return (
{render?.(column ?? data, data, rowIndex) || column}
); }}
); }; return ( ); }); const rowHeights = { large: 54, middle: 46, small: 38 }; const columnPadding = { large: 16, middle: '12px 8px', small: 8 };