import React, {useEffect, useState, useRef} from 'react';
import {Table} from 'antd';
// @ts-ignore
import {Resizable} from 'react-resizable';
// @ts-ignore
import classNames from 'classnames';
import './index.less';
const ResizableTitle = (props: any) => {
const {onResize, width, ...restProps} = props;
// 添加偏移量
const [offset, setOffset] = useState(0);
if (!width) {
return
| ;
}
return (
{
e.stopPropagation();
e.preventDefault();
}}
/>
}
onResize={(_e: any, {size}: any) => {
// 这里只更新偏移量,数据列表其实并没有伸缩
setOffset(size.width - width);
}}
// 拖拽结束更新
onResizeStop={(...arg: any) => {
// 拖拽结束以后偏移量归零
setOffset(0);
onResize(...arg);
}}
draggableOpts={{enableUserSelectHack: false}}
>
|
);
};
const GTable: React.FC = (props) => {
const {columns, resizable, virtual, ...restProps} = props;
const [mergedColumns, setMergedColumns] = useState([]);
const columnsWidthRef = useRef({});
const columnsRef = useRef([]);
const handleResize = (index: number) => (_e: any, {size}: any) => {
const nextColumns = [...columnsRef.current];
nextColumns[index] = {
...nextColumns[index],
width: size.width,
};
const tempContainer = {...columnsWidthRef.current};
const name = nextColumns[index].dataIndex || '';
tempContainer[name] = size.width;
columnsWidthRef.current = tempContainer;
setMergedColumns(nextColumns);
};
useEffect(() => {
columnsRef.current = mergedColumns;
}, [mergedColumns]);
const mergeColumns = () => {
const list = columns.map((x: any, index: number) => {
const obj = {...x};
// 拖拽拉伸
if (resizable && !obj.onHeaderCell) {
const width = columnsWidthRef.current[obj.dataIndex];
if (width) {
obj.width = width;
}
obj.onHeaderCell = (column: any) => ({
width: column.width,
onResize: handleResize(index),
});
}
const {ellipsis} = obj;
if (ellipsis !== false) {
obj.ellipsis = true;
}
return obj;
});
setMergedColumns(list);
};
useEffect(() => {
if (columns.length > 0) {
mergeColumns();
}
}, [columns]);
const components = {
header: {
cell: ResizableTitle,
},
};
return (
{mergedColumns.length > 0 ? (
{
let className = '';
if (index % 2 === 1) className = 'darkRow';
return className;
}}
size="small"
{...restProps}
columns={mergedColumns}
components={components}
/>
) : null}
);
};
export default GTable;