DraggableBodyRow.jsx 1.33 KB
Newer Older
1
import React, { useRef, useState, useEffect } from 'react';
2
import { useDrag, useDrop } from 'react-dnd';
邓超's avatar
邓超 committed
3 4
import classnames from 'classnames';
import styles from './index.less';
5 6 7 8 9 10 11 12

const DraggableBodyRow = ({
  name,
  index,
  moveRow,
  className,
  style,
  tableType,
13
  ItemTypes,
14 15
  ...restProps
}) => {
16
  const [type, setType] = useState('');
17
  const ref = useRef();
18 19 20 21 22
  useEffect(() => {
    if (ItemTypes) {
      setType(ItemTypes);
    }
  }, [ItemTypes]);
23
  const [{ isOver, dropClassName }, drop] = useDrop({
24
    accept: type,
25 26 27 28 29 30 31 32
    collect: monitor => {
      const { index: dragIndex } = monitor.getItem() || {};
      if (dragIndex === index) {
        return {};
      }
      return {
        isOver: monitor.isOver(),
        canDrop: monitor.canDrop(),
33
        dropClassName: dragIndex < index ? 'drop-over-downward' : 'drop-over-upward',
34 35 36 37 38 39 40
      };
    },
    drop: item => {
      moveRow(item.index, index, tableType);
    },
  });
  const [, drag] = useDrag({
41
    type,
42 43 44 45 46 47 48 49 50
    item: { index },
    collect: monitor => ({
      isDragging: monitor.isDragging(),
    }),
  });
  drop(drag(ref));
  return (
    <tr
      ref={ref}
邓超's avatar
邓超 committed
51 52 53 54
      className={classnames({
        [className]: true,
        [styles[dropClassName]]: isOver,
      })}
55 56 57 58 59 60 61
      style={{ cursor: 'move', ...style }}
      {...restProps}
    />
  );
};

export default DraggableBodyRow;