使用有层级结构的数据
树数据结构 - 将分层数据可视化为可展开的树
分层数据结构
功能概述
本示例演示将分层数据结构可视化为树。层级的每一层都清晰分离,父子关系通过连接线显示。支持展开/折叠分支以专注于树的特定部分。
核心特性实现
递归树构建
const buildTreeFromData = (data: TreeNode, parentId?: string): RGJsonData => {
const nodes: JsonNode[] = [{
id: data.id,
text: data.label,
data: { level: data.level, expanded: true }
}];
const lines: JsonLine[] = [];
if (parentId) {
lines.push({ from: parentId, to: data.id });
}
if (data.children) {
data.children.forEach(child => {
const childGraph = buildTreeFromData(child, data.id);
nodes.push(...childGraph.nodes);
lines.push(...childGraph.lines);
});
}
return { nodes, lines };
};
基于级别的样式
const applyLevelStyles = (node: RGNode) => {
const level = node.data.level;
const colors = ['#1a237e', '#0d47a1', '#01579b', '#0277bd'];
return {
color: colors[level % colors.length],
fontSize: Math.max(12, 20 - level * 2)
};
};
展开/折叠处理器
const onNodeExpand = (node: RGNode) => {
const children = graphInstance.getNodes().filter(n =>
graphInstance.getLineById(`${node.id}-${n.id}`)
);
children.forEach(child => {
graphInstance.updateNode(child, { hidden: false });
});
};
const onNodeCollapse = (node: RGNode) => {
const descendants = getAllDescendants(node);
descendants.forEach(desc => {
graphInstance.updateNode(desc, { hidden: true });
});
};
创意使用场景
组织架构图:企业层级和报告结构。
文件系统:目录和文件层级。
分类法:生物分类或产品类别。
决策树:复杂的决策结构。
技能树:学习进度和先决条件。