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

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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
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、使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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 @   信铁寒胜  阅读(1229)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示