1、效果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/a03fdb44a577bfd7f9225e7aa5de7393.gif#pic_center)
2、代码
import React, { useState } from "react";
import "./index.css";
import { Tree } from "antd";
import type { DataNode } from "antd/es/tree";
const treeData: DataNode[] = [
{
title: "0-0",
key: "0-0",
children: [
{
title: "0-0-0",
key: "0-0-0",
children: [
{
title: "0-0-0-0",
key: "0-0-0-0",
children: [
{ title: "0-0-0-0-1", key: "00--0-0-1" },
{ title: "0-0-0-0-2", key: "0-0-0-0-2" },
],
},
{ title: "0-0-0-1", key: "0-0-0-1" },
{ title: "0-0-0-2", key: "0-0-0-2" },
],
},
{
title: "0-0-1",
key: "0-0-1",
children: [
{ title: "0-0-1-0", key: "0-0-1-0" },
{ title: "0-0-1-1", key: "0-0-1-1" },
{ title: "0-0-1-2", key: "0-0-1-2" },
],
},
{
title: "0-0-2",
key: "0-0-2",
},
],
},
{
title: "0-1",
key: "0-1",
children: [
{ title: "0-1-0-0", key: "0-1-0-0" },
{ title: "0-1-0-1", key: "0-1-0-1" },
{ title: "0-1-0-2", key: "0-1-0-2" },
],
},
{
title: "0-2",
key: "0-2",
},
];
const App: React.FC = () => {
const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
const onExpand = (expandedKeysValue: React.Key[], { node: { key } }) => {
setExpandedKeys(expandedKeysValue);
setSelectedKeys([key]);
};
const onSelect = (selectedKeysValue: React.Key[], { node: { key } }) => {
setExpandedKeys((prevKeys) => {
const newArr = new Set(expandedKeys);
if (newArr.has(key)) {
newArr.delete(key);
} else {
newArr.add(key);
}
return [...newArr];
});
setSelectedKeys([key]);
};
return (
<Tree
onExpand={onExpand}
expandedKeys={expandedKeys}
onSelect={onSelect}
selectedKeys={selectedKeys}
treeData={treeData}
/>
);
};
export default App;