Antd ProTable 设置表格头,可拖动变换列宽度

ProTable 表格本身是不支持,列宽度可拖动的。

1、按照一个插件( react-resizable)npm install --save react-resizable

2、新建一个工具类ResizableTableUtil.js

import React from 'react';
import { Resizable } from 'react-resizable';

const ResizableTitle = (props) => {
    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 getMergeColumns = (columns,setColumns) =>{
    const mergeColumns = columns.map((col, index) => ({
        ...col,
        onHeaderCell: (column) => ({
            width: column.width,
            onResize: handleResize(
                index,
                columns,
                (value) => setColumns(value)
            ),
        }),
      }));
    return mergeColumns
  }
  
  export const handleResize = (index, columns, setColumns) => (_, { size }) => {
    const newColumns = [...columns];
    newColumns[index] = {
      ...newColumns[index],
      width: size.width,
    };
    setColumns(newColumns);
  };

 2、使用

import {components,getMergeColumns} from './ResizableTableUtil';

const data = [{name:"123",age:123,name:"456",age:111}]/* 你的数据源 */;

const MyProTable = () => {
  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 = getMergeColumns(columns,setColumns)
  return (
    <ProTable
      columns={mergeColumns}
      dataSource={data}
      components={components}
    />
  );
};

  最终效果:

 

posted @ 2024-03-19 14:34  信铁寒胜  阅读(207)  评论(0编辑  收藏  举报