Ⅰ- 壹 - 功能展示和使用需求
需求描述
同级拖拽,不能不同父级的进行拖拽
功能展示
Ⅱ - 贰 - 封装代码
import React, { useState } from "react";
import { Tree } from "antd";
import { cloneDeep } from "lodash";
const dataA = [
{
title: "Branch 1",
key: "1",
parentId: '0',
leve: 0,
children: [
{
title: "Branch 1.1",
key: "1.1",
parentId: '1',
leve: 1,
},
{
title: "Branch 1.2",
key: "1.2",
parentId: '1',
leve: 1,
},
{
title: "Branch 1.3",
key: "1.3",
parentId: '1',
leve: 1,
},
],
},
{
title: "Branch 2",
key: "2",
parentId: '0',
leve: 0,
children: [
{
title: "Branch 2.1",
key: "2.1",
parentId: '2',
leve: 1,
},
{
title: "Branch 2.2",
key: "2.2",
parentId: '2',
leve: 1,
},
],
},
{
title: "Branch 3",
key: "3",
parentId: '0',
leve: 0,
children: [
{
title: "Branch 3.1",
key: "3.1",
parentId: '3',
leve: 1,
},
{
title: "Branch 3.2",
key: "3.2",
parentId: '3',
leve: 1,
},
{
title: "Branch 3.3",
key: "3.3",
parentId: '3',
leve: 1,
},
],
},
];
export default function Demo() {
const [treeData, setTreeData] = useState(dataA);
const onDrop = (info) => {
console.log("info", info);
const dragNode = info.dragNode;
const dropNode = info.node;
// const dropKey = info.node.props.eventKey;
// const dragKey = info.dragNode.props.eventKey;
// const dropPos = info.node.props.pos.split('-');
// const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);
// console.log(info, "info");
// console.log(dropKey, "dropKey", "放置位置同级的上一个元素,当最顶的时候是下一个元素");
// console.log(dragKey, "dragKey", "拖拽对象");
// console.log(dropPos, "dropPos","应该没什么用,拿来计算dropPosition = -1的参数而已");
// console.log(dropPosition, "dropPosition", "-1的时候是最顶的最顶,");
// console.log(info.dropToGap, "dropToGap", "最外一层的第一个是true,移动到其他树枝的第一个时是false,移动到不是第一个的位置是true");
// ————————————————
// 版权声明:本文为CSDN博主「没事下辈子小心点」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
// 原文链接:https://blog.csdn.net/weixin_42357617/article/details/120422339
if (dropNode.parentId != dragNode.parentId && dropNode.key != dragNode.parentId) {
console.log('提示---不可以不同父级进行拖拽');
return
}
let clodata = cloneDeep(treeData)
const loopSplice = (data) => {
let cIndex = data.findIndex((o: any) => o.key == dragNode.key)
let cItem = data.find((o: any) => o.key == dragNode.key)
console.log(cIndex, "===cIndex==");
console.log(info.dropPosition, "===info.dropPosition==");
console.log(cIndex >= info.dropPosition ? info.dropPosition : info.dropPosition - 1, "===info.dropPosition tow==");
data.splice(cIndex, 1);
if (!info.dropToGap || info.dropPosition == -1) {
data.splice(0, 0, cItem);
} else {
data.splice(cIndex >= info.dropPosition ? info.dropPosition : info.dropPosition - 1, 0, cItem);
}
}
const loop = (data) => {
if (dragNode.parentId == 0) {
loopSplice(data)
return
}
for (const iterator of data) {
if (iterator.key == dragNode.parentId) {
loopSplice(iterator.children)
return
}
if (iterator?.children) loop(iterator?.children)
}
};
loop(clodata)
setTreeData(() => clodata)
}
return (
<div>
<Tree defaultExpandAll draggable treeData={treeData} onDrop={onDrop} />
</div>
);
}