react antdesign table列可拖拽调整宽度

场景

公司要求table列可以拖拽调整宽度,在antd版本4文档中,没有此功能,但是在antd3版本里有此功能,写法在antd4 antd5中同样适用。以下为优化后代码,可直接复制使用。

1. 安装包

# 安装包 实现可拖拽列
yarn add react-resizable

2. 写法

js


import React from 'React'
import { Table } from 'antd';
import 'react-resizable'
import { Resizable } from 'react-resizable';
import styles from './index.less'

const ResizeableTitle = props => {
  const { onResize, width, ...restProps } = props;

  if (!width) {
    return <th {...restProps} className={styles.resizableTh}/>;
  }

  return (
    <Resizable
      width={width}
      height={0}
      onResize={onResize}
      draggableOpts={{ enableUserSelectHack: false }}
      handle={
      	<span onClick={e => e.stopPropagation()} className={styles.resizableHandle}></span>
      }
    >
      <th {...restProps} className={styles.resizableTh}/>
    </Resizable>
  );
};

class Demo extends React.Component {
  state = {
    columns: [
      {
        title: 'Date',
        dataIndex: 'date',
        width: 200,
      },
      {
        title: 'Amount',
        dataIndex: 'amount',
        width: 100,
      },
    ],
  };

  components = {
    header: {
      cell: ResizeableTitle,
    },
  };

  data = [
    {
      key: 0,
      date: '2018-02-11',
      amount: 120,
    },
  ];

  handleResize = index => (e, { size }) => {
    this.setState(({ columns }) => {
      const nextColumns = [...columns];
      nextColumns[index] = {
        ...nextColumns[index],
        width: size.width,
      };
      return { columns: nextColumns };
    });
  };

  render() {
    const columns = this.state.columns.map((col, index) => ({
      ...col,
      onHeaderCell: column => ({
        width: column.width,
        onResize: this.handleResize(index),
      }),
    }));

    return <Table bordered components={this.components} columns={columns} dataSource={this.data} />;
  }
}

export default Demo;

index.less

.resizableHandle {
  border-right: 1px solid #e8e8e8;
  position: absolute;
  top: 50%;
  right: 0;
  transform: translateY(-50%);
  z-index: 1;
  width: 10px;
  height: calc(100% - 20px);
  cursor: col-resize;
}

.resizableTh {
  overflow: visible;
}

.resizableTh:last-child {
  overflow: hidden;
  .resizableHandle{
    display: none;
  }
}

注意事项

  1. columns配置必须配置列宽度width,且为number类型,否则不会出现拖拽标识或者拖拽无效。
  2. 一定要设置样式

你可能感兴趣的:(react,react.js)