表格拖拽排序之react-dnd---结合antd Table

实现效果

表格拖拽排序之react-dnd---结合antd Table_第1张图片

首先引入react-dnd需要的npm包

import { DndProvider, DragSource, DropTarget } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import update from 'immutability-helper';

其次设置Table中的onRow和component属性


components={component}
onRow={ (record, index) => ({
  index,
  moveRow: this.moveRow,
})}

moveRow方法:

  moveRow = (dragIndex, hoverIndex) => {
    const { dataSource } = this.state;
    const dragRow = dataSource[dragIndex];
    this.setState(
      update(this.state, {
        dataSource: {
          $splice: [[dragIndex, 1], [hoverIndex, 0, dragRow]],
        },
      }));
    this.setState({
      hasChanged: true,
    });
  };

引入components

import React from 'react';
import { DragSource, DropTarget } from 'react-dnd';

let dragingIndex = -1;
const BodyRow = (props) => {
  const { isOver, connectDragSource, connectDropTarget, moveRow,
    ...restProps } = props;
  const styleY = { ...restProps.style, cursor: 'move' };
  let { className } = restProps;
  if (isOver) {
    if (restProps.index > dragingIndex) {
      className += ' drop-over-downward';
    }
    if (restProps.index < dragingIndex) {
      className += ' drop-over-upward';
    }
  }
  return connectDragSource(
    connectDropTarget(),
  );
};

const rowSource = {
  beginDrag(props) {
    dragingIndex = props.index;
    return {
      index: props.index,
    };
  },
};

const rowTarget = {
  drop(props, monitor) {
    const dragIndex = monitor.getItem().index;
    const hoverIndex = props.index;
    if (dragIndex === hoverIndex) {
      return;
    }
    props.moveRow(dragIndex, hoverIndex);
    const mon = monitor.getItem();
    mon.index = hoverIndex;
  },
};

const DragableBodyRow = DropTarget('row', rowTarget, (connectIn, monitor) => ({
  connectDropTarget: connectIn.dropTarget(),
  isOver: monitor.isOver(),
  dragingIndex,
}))(
  DragSource('row', rowSource, con => ({
    connectDragSource: con.dragSource(),
  }))(BodyRow),
);


export const component = {
  body: {
    row: DragableBodyRow,
  },
};

 

你可能感兴趣的:(react-dnd,拖拽排序)