forked from nsjcy/frontEnd/nsjcy

LiuWenHaoU
2020-05-18 bd09ddbe5eae5e780393d37b72b4da6d4e92fdb8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import React from 'react';
 
let curDragIndex = null;
 
export default function DragSort(props) {
  let container = props.children;
  let draggable = props.draggable;
 
  function onChange(from, to) {
    let curValue = props.data;
    let newValue = arrMove(curValue, from, to);
    if (typeof props.onDragMove === 'function') {
      return props.onDragMove(newValue, from, to);
    }
  }
  return (
    <div>
      {container.map((item, index)=>{
        if(React.isValidElement(item)){
          return React.cloneElement(item, {
            draggable,
            //开始拖动元素时触发此事件 
            onDragStart(){
              curDragIndex = index;
            },
            /*
             * 当被拖动的对象进入其容器范围内时触发此事件
             * 在自身拖动时也会触发该事件
             */
            onDragEnter() {
              onChange(curDragIndex, index);
              curDragIndex = index;
            },
            /* 
             * 当被拖动的对象在另一对象容器范围内拖动时触发此事件
             * 在拖动元素时,每隔350毫秒会触发onDragOver事件
             */
            onDragOver(e) {
              /*
               * 默认情况下,数据/元素不能放置到其他元素中。如果要实现该功能,我们需要
               * 防止元素的默认处理方法,我们可以通过调用event.preventDefault()方法来实现onDragOver事件
               */
              e.preventDefault();
            },
            //完成元素拖动后触发
            onDragEnd(){
              curDragIndex = null;
              if(typeof props.onDragEnd === 'function'){
                props.onDragEnd(index);
              };
            },
          })
        }
        return item;
      })}
    </div>
  );
}
 
function arrMove(arr, fromIndex, toIndex) {
  if (fromIndex !== toIndex) {
    arr = arr.concat();
    let item = arr.splice(fromIndex, 1)[0];
    arr.splice(toIndex, 0, item);
  };
  return arr;
}