Tree.js
javascript
import Taro, { useState } from '@tarojs/taro';
import { View, Text, Button } from '@tarojs/components';
import './Tree.scss';
const TreeNode = ({ node, onSelect, onExpand }) => {
const handleNodeClick = () => {
onSelect && onSelect(node.id);
};
const handleExpandClick = () => {
onExpand && onExpand(node.id);
};
return (
<View className="tree-node">
<Text className="title" onClick={handleNodeClick}>
{node.title}
</Text>
{node.children && node.children.length > 0 && (
<Button className="expand-btn" onClick={handleExpandClick}>
{node.expanded ? '-' : '+'}
</Button>
)}
{node.expanded && node.children && node.children.length > 0 && (
<View className="children">
{node.children.map((child) => (
<TreeNode
key={child.id}
node={child}
onSelect={onSelect}
onExpand={onExpand}
/>
))}
</View>
)}
</View>
);
};
const Tree = () => {
const [treeData, setTreeData] = useState([
{
id: '1',
title: 'Node 1',
children: [
{
id: '1-1',
title: 'Node 1-1',
children: [
{
id: '1-1-1',
title: 'Node 1-1-1',
children: [
{ id: '1-1-1-1', title: 'Node 1-1-1-1', children: [] },
{ id: '1-1-1-2', title: 'Node 1-1-1-2', children: [] },
],
},
{
id: '1-1-2',
title: 'Node 1-1-2',
children: [],
},
],
},
{
id: '1-2',
title: 'Node 1-2',
children: [
{
id: '1-2-1',
title: 'Node 1-2-1',
children: [],
},
{
id: '1-2-2',
title: 'Node 1-2-2',
children: [],
},
],
},
],
},
]);
const handleNodeSelect = (id) => {
console.log('Selected Node:', id);
};
const handleNodeExpand = (id) => {
setTreeData((prevTreeData) => {
return toggleNodeExpanded(prevTreeData, id);
});
};
const toggleNodeExpanded = (data, id) => {
return data.map((node) => {
if (node.id === id) {
return {
...node,
expanded: !node.expanded,
};
} else if (node.children && node.children.length > 0) {
return {
...node,
children: toggleNodeExpanded(node.children, id),
};
}
return node;
});
};
return (
<View className="tree">
{treeData.map((node) => (
<TreeNode
key={node.id}
node={node}
onSelect={handleNodeSelect}
onExpand={handleNodeExpand}
/>
))}
</View>
);
};
export default Tree;
Tree.scss
javascript
.tree {
.tree-node {
display: flex;
align-items: center;
margin-bottom: 10px;
.title {
flex-grow: 1;
cursor: pointer;
}
.expand-btn {
width: 20px;
height: 20px;
line-height: 20px;
margin-left: 5px;
font-size: 16px;
}
&.children {
margin-left: 10px;
}
}
}
引用Tree.js的主页面index.js
javascript
import Taro, { Component } from '@tarojs/taro';
import { View } from '@tarojs/components';
import Tree from '../../components/Tree';
class Index extends Component {
config = {
navigationBarTitleText: '首页',
};
render() {
return (
<View>
<Tree />
</View>
);
}
}
export default Index;
具体的样式大家可以根据需求手动调整。