在antd Table 实现拖动调整列宽

需求
拖动表头的每一列,调整列宽度

方案
使用[React-Resizable]()实现拖动更改宽度

示例代码

import React, { useState, useEffect } from 'react'
import { Resizable } from 'react-resizable'
import { Table } from 'antd'
// 需要引入resizziable的样式
// import "../node_modules/react-resizable/css/styles.css";

const dataSource = [
{
  key: '1',
  name: '胡彦斌',
  age: 32,
  address: '西湖区湖底公园1号',
},
{
  key: '2',
  name: '胡彦祖',
  age: 42,
  address: '西湖区湖底公园1号',
},
]

const columns = [
{
  title: 'Full Name',
  dataIndex: 'name',
  key: 'name',
  fixed: 'left',
},
{
  title: 'Age',
  dataIndex: 'age',
  key: 'age',
  fixed: 'left',
},
{
  title: 'Column 1',
  dataIndex: 'address',
  key: '1',
},
{
  title: 'Column 2',
  dataIndex: 'address',
  key: '2',
},
{
  title: 'Column 3',
  dataIndex: 'address',
  key: '3',
},
{
  title: 'Column 4',
  dataIndex: 'address',
  key: '4',
},
{
  title: 'Column 5',
  dataIndex: 'address',
  key: '5',
},
{
  title: 'Action',
  key: 'operation',
  fixed: 'right',
  render: () => <a>action</a>,
},
]

const ResizableTitle = props => {
const {
  onResize, className, width = 100, title, children, ...restProps
} = props
// ! 让antd的样式和resizable的样式共存
const sty = _.merge(props, restProps)

return (
  <Resizable width={width} height={0} onResize={onResize}>
    <th {...sty}>{children}</th>
  </Resizable>
)
}

const ResizableTest = () => {
const [column, setColumn] = useState(columns)

const handleResize = (col, size, oldColumn) => {
  const newColumns = [...oldColumn]
  newColumns.forEach(item => {
    if (item.key === col.key) {
      item.width = size.width
    }
  })

  setColumn(newColumns)
}

useEffect(() => {
  const newColumn = [...column].map(it => (
    {
      ...it,
      ellipsis: {
        showTitle: true,
      },
      onHeaderCell: col => ({
        width: col.width,
        // !传入newColumn,而不传入column是因为需要拿到有onHeaderCell的值,外面collumn的变化内部监听不到
        onResize: (e, { size }) => handleResize(col, size, newColumn),
      }),
    }
  ))
  setColumn(newColumn)
}, [])

return (
  <Table
    columns={column}
    dataSource={dataSource}
    components={{
      header: {
        cell: ResizableTitle,
      },
    }}
  />
)
}

export default ResizableTest

效果

初始化
img

拖动后
img

posted @ 2022-05-18 15:37  VictoriaC~  阅读(4717)  评论(2编辑  收藏  举报