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. 一定要设置样式
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值