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
68
69
70
71
import React, { useState, useEffect } from 'react';
import { Table } from 'antd';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { DndProvider } from 'react-dnd';
import DraggableBodyRow from './DraggableBodyRow';
const DragTable = props => {
const { columns, dataSource, dragCallBack, ItemTypes } = props;
const [data, setData] = useState(null); // 分组后的数组
const components = {
body: {
row: DraggableBodyRow,
},
};
useEffect(() => {
if (dataSource.length > 0) {
setData(dataSource);
}
}, [dataSource]);
// 每次拖拽后返回
useEffect(() => {
dragCallBack(data);
}, [data]);
// 移动数组元素到指定位置
const moveInArray = (arr, from, to) => {
// 确保是有效数组
if (Object.prototype.toString.call(arr) !== '[object Array]') {
throw new Error('Please provide a valid array');
}
// 删除当前的位置
let item = arr.splice(from, 1);
// 确保还剩有元素移动
if (!item.length) {
throw new Error(`There is no item in the array at index ${from}`);
}
// 移动元素到指定位置
arr.splice(to, 0, item[0]);
return arr;
};
// 拖拽表格
const moveRow = (dragIndex, hoverIndex) => {
setData(val => {
let newData = JSON.parse(JSON.stringify(val));
newData = moveInArray(newData, dragIndex, hoverIndex);
return newData;
});
};
return (
<div>
<DndProvider backend={HTML5Backend}>
<Table
bordered
columns={columns}
dataSource={data}
components={components}
onRow={(record, index) => ({
index,
ItemTypes,
moveRow,
onClick: () => props.onClick && props.onClick(record),
})}
{...props}
/>
</DndProvider>
</div>
);
};
export default DragTable;