要求支持展示,点击展开和折叠。
首先定义一个数据结构
const directoryData = [
{
id: 1,
name: 'Folder 1',
children: [
{
id: 2,
name: 'Folder 1.1',
children: [
{ id: 3, name: 'File 1.1.1' },
{ id: 4, name: 'File 1.1.2' }
]
},
{ id: 5, name: 'File 1.2' }
]
},
{
id: 6,
name: 'Folder 2',
children: [
{ id: 7, name: 'File 2.1' }
]
}
];
递归渲染
import React, { useState } from 'react';
const DirectoryTree = ({ data }) => {
return (
<ul>
{data.map(item => (
<DirectoryNode key={item.id} node={item} />
))}
</ul>
);
};
const DirectoryNode = ({ node }) => {
const [isOpen, setIsOpen] = useState(false);
const handleToggle = () => {
setIsOpen(!isOpen);
};
return (
<li>
<div onClick={handleToggle} style={{ cursor: 'pointer' }}>
{node.children && (isOpen ? '[-] ' : '[+] ')}
{node.name}
</div>
{isOpen && node.children && (
<DirectoryTree data={node.children} />
)}
</li>
);
};
// 示例
const App = () => {
return (
<div>
<h1>Directory Tree</h1>
<DirectoryTree data={directoryData} />
</div>
);
};
export default App;