基于antd Tree实现可编辑菜单树,支持节点新增、删除
以下是一个使用Ant Design的Tree组件实现可编辑菜单树的基本示例,包括节点的新增和删除功能。
import React, { useState } from 'react';
import { Tree, Input, Button, Space } from 'antd';
import {
PlusOutlined,
MinusOutlined,
EditOutlined,
} from '@ant-design/icons';
const MenuEditor = () => {
const [treeData, setTreeData] = useState([
{ title: '0-0', key: '0-0', children: [{ title: '0-0-0', key: '0-0-0' }] },
]);
const [editKey, setEditKey] = useState(null);
const addTreeNode = (key, newNode) => {
setTreeData(data =>
data.map(item => {
if (item.key === key) {
if (!item.children) {
item.children = [];
}
item.children.push({ title: newNode, key: `${key}-${item.children.length}` });
}
return item;
}),
);
};
const removeTreeNode = (key, nodeKey) => {
setTreeData(data =>
data.map(item => {
if (item.key === key) {
item.children = item.children.filter(child => child.key !== nodeKey);
}
return item;
}),
);
};
const handleAdd = (key, e) => {
const newNode = e.target.value;
if (newNode) {
addTreeNode(key, newNode);
}
};
const handleRemove = (key, nodeKey) => {
removeTreeNode(key, nodeKey);
};
const handleEdit = (key, title) => {
setTreeData(data =>
data.map(item => {
if (item.key === key) {
item.title = title;
}
return item;
}),
);
};
const onDrop = info => {
const { node, dragNode, dropPosition } = info;
const dragKey = dragNode.key;
const dropKey = node.key;
// 更新节点信息
setTreeData(data => {
const loop = data =>
data.map(item => {
if (item.key === dropKey) {
const ar = item.children || [];
ar.splice(dropPosition + (dragNode.children ? dragNode.children.length : 0), 0, {
key: dragKey,
title: dragNode.title,
});
item = { ...item, children: ar };
} else {
if (item.children) {
item = { ...item, children: loop(item.children) };
}
}
return item;
});
return loop(data);
});
};
const onCheck = (checkedKeys, info) => {
console.lo
评论已关闭