antd react 表格开发: 列宽拉伸触发排序事件,问题修复(react-resizable拖拽)

1,176 阅读1分钟

antd react 表格开发: 列宽拉伸触发排序事件,问题修复

拖动列宽的表格组件,通过resizing字段控制,Resizable的onResizeStart,onResizeStop属性进行判断,实现拖动时防止误触。

import { Table } from 'antd';
import { Resizable } from 'react-resizable';

const ResizeableTitle = props => {
  const { onResize, width,onClick, ...restProps } = props;
  let resizing = false; //定义变量存储是否在拖拽中
  if (!width) {
    return <th {...restProps} />;
  }

  return (
    <Resizable
      width={width}
      height={0}
      onResize={onResize}
      onResizeStart = {() => {
        resizing = true;
      }}
      onResizeStop= {() => {
        resizing = true;
        setTimeout(() =>{
           resizing = false;
        },100);
      }}
      draggableOpts={{ enableUserSelectHack: false }}
    >
      <th {...restProps} onClick={(...args) => {
          if(!resizing){
            onClick(...args)
          }
        }}
        />
    </Resizable>
  );
};

class Demo extends React.Component {
  state = {
    columns: [
      {
        title: 'Date',
        dataIndex: 'date',
         sortOrder:true,
        width: 200,
      },
      {
        title: 'Amount',
        dataIndex: 'amount',
         sortOrder:true,
        width: 100,
      },
      {
        title: 'Type',
        dataIndex: 'type',
         sortOrder:true,
        width: 100,
      },
      {
        title: 'Note',
        dataIndex: 'note',
         sortOrder:true,
        width: 100,
      },
      {
        title: 'Action',
        key: 'action',
        render: () => <a>Delete</a>,
      },
    ],
  };

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

  data = [
    {
      key: 0,
      date: '2018-02-11',
      amount: 120,
      type: 'income',
      note: 'transfer',
    },
    {
      key: 1,
      date: '2018-03-11',
      amount: 243,
      type: 'income',
      note: 'transfer',
    },
    {
      key: 2,
      date: '2018-04-11',
      amount: 98,
      type: 'income',
      note: 'transfer',
    },
  ];

  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} />;
  }
}

ReactDOM.render(<Demo />, mountNode);

若有收获,就点个赞吧