import React, { useEffect, useState } from 'react'; import { Table } from "antd"; import { Resizable } from 'react-resizable'; import "./index.css"; const ResizableTitle = props => { const { onResize, width, ...restProps } = props; // useEffect(() => { // // 使用选择器,获取所有拖动按钮的 Dom 对象 // document.querySelectorAll('.react-resizable-handle').forEach((elem) => { // if (elem['onclick']) { // return; // } // elem['onclick'] = (event) => { // // 阻止冒泡 // event.stopPropagation(); // return false; // }; // }); // }, []); // 没有原始宽度的列,不支持伸缩;会出现从自适应宽度一下子跳到拖动位置;也可以自行增加参数,如 disableResize if (!width) { return ; } return ( { e.stopPropagation() }} /> } > ); }; const ResizableTable = props => { const { columns: columns_, components: components_, onChangeResize, tableLayout, ...other } = props // const [columns, setColumns] = useState(columns_.map((col) => { // col['onHeaderCell']=(col) => ({ // ...col['onHeaderCell'], // width: col.width, // onResize: handleResize(col.dataIndex), // }) // return col; // } // )); const [columns, setColumns] = useState([]); // 每一列增加 width, onResize 作为 ResizableTitle 的 props useEffect(() => { columns_.forEach((col) => ( col['onHeaderCell'] = (col) => ({ width: col.width, onResize: handleResize(col.dataIndex), }) ) ); setColumns(columns_); }, [columns_]); // 拖动时更新表格列 let handleResize = dataIndex => (e, { size }) => { setColumns((columns) => ( columns.map((column) => { if (column.dataIndex === dataIndex) { return { ...column, width: size.width, }; } else { return column; } }) )); onChangeResize && onChangeResize({ [dataIndex]: size.width }); // 列尺寸缓存本地 }; const components = { ...components_, header: { cell: ResizableTitle } } return ; } export default ResizableTable;