参照来源https://blog.csdn.net/Violent_clown/article/details/107834668antd pro支持antd的组件属性,pro没有写详细的可以先查看一下antd官方文档表格 Table - Ant Design
1. 安装 react-resizable 插件
npm i --save react-resizable
yarn add react-resizable
2. 复制官方例子,实现Table的可伸缩效果,注意要引入css样式
3. 二次封装拉伸组件
新建公共组件目录ResizableTable -> index.tsx、index.less
index.tsx代码
import React from 'react';
import type { ResizeCallbackData } from 'react-resizable';
import { Resizable } from 'react-resizable';
import './index.less';
const ResizableTitle = (
props: React.HTMLAttributes<any> & {
onResize: (e: React.SyntheticEvent<Element>, data: ResizeCallbackData) => void;
width: number;
},
) => {
const { onResize, width, ...restProps } = props;
if (!width) {
return <th {...restProps} />;
}
return (
<Resizable
width={width}
height={0}
handle={
<span
className="react-resizable-handle"
onClick={(e) => {
e.stopPropagation();
}}
/>
}
onResize={onResize}
draggableOpts={{ enableUserSelectHack: false }}
>
<th {...restProps} />
</Resizable>
);
};
export const components = {
header: {
cell: ResizableTitle,
},
};
export const handleResize: Function =
(
index: number,
columns: (
| { title: string; dataIndex: string; render?: undefined; width: number }
| { title: string; dataIndex: string; render: (text: string) => any; width: number }
)[],
setColumns: Function,
) =>
(_: React.SyntheticEvent<Element>, { size }: ResizeCallbackData) => {
const newColumns = [...columns];
newColumns[index] = {
...newColumns[index],
width: size.width,
};
setColumns(newColumns);
};
index.less
.react-resizable {
position: relative;
background-clip: padding-box;
}
.react-resizable-handle {
position: absolute;
right: -5px;
bottom: 0;
z-index: 1;
width: 10px;
height: 100%;
cursor: col-resize;
}
4. 界面引用
import { components, handleResize } from '@/components/ResizableTable';
import { ProTable } from '@ant-design/pro-components';
const [columns, setColumns] = useState([
{
title: 'Date',
dataIndex: 'date',
width: 200,
},
{
title: 'Note',
dataIndex: 'note',
width: 100,
},
{
title: 'Action',
key: 'action',
render: () => <a>Delete</a>,
},
]);
const mergeColumns = columns.map((col, index) => ({
...col,
onHeaderCell: (column: { width: number }) => ({
width: column.width,
onResize: handleResize(
index,
columns,
(
value: React.SetStateAction<
{ title: string; dataIndex: string; render?: (text: string) => any; width: number }[]
>,
) => setColumns(value),
),
}),
}));
<ProTable
components={components}
columns={mergeColumns}
...
/>;
*/
注意
1. columns数组一定要包含width属性
2. DragSortTable 拖拽不生效,用ProTable可以 ( "@ant-design/pro-components": "^2.6.48")