Arco Design Tree组件选中节点后怎么获取完整路径?

UP主~艳杰 阅读 4

我用 Arco Design 的 Tree 组件做了一个菜单选择功能,现在想在用户点击某个节点时拿到从根到该节点的完整路径(比如 [‘parent’, ‘child’, ‘current’]),但文档里没找到直接的方法。

试过 onSelect 回调里的 selectedKeysnode 参数,但只能拿到当前节点信息,没法往上追溯父级。难道要自己遍历整棵树找路径?有没有更简单的方式?

这是我的数据结构:

const treeData = [
  {
    key: '1',
    title: 'Parent',
    children: [
      {
        key: '2',
        title: 'Child',
        children: [
          { key: '3', title: 'Current' }
        ]
      }
    ]
  }
];
我来解答 赞 1 收藏
二维码
手机扫码查看
1 条解答
司徒彦杰
直接上代码,预先处理一下就行:

import { Tree } from '@arco-design/web-react';

// 先把树展平,构建 key -> 完整路径 的映射
const buildPathMap = (data, parentPath = []) => {
const map = {};

data.forEach(node => {
const currentPath = [...parentPath, node.key];
map[node.key] = currentPath;

if (node.children) {
Object.assign(map, buildPathMap(node.children, currentPath));
}
});

return map;
};

// 组件中
const pathMap = buildPathMap(treeData);

const handleSelect = (selectedKeys) => {
const fullPath = pathMap[selectedKeys[0]];
console.log(fullPath); // ['1', '2', '3']
};

return (
<Tree
treeData={treeData}
onSelect={handleSelect}
/>
);


如果想拿到 title 路径而不是 key,改一下就行:

const buildTitlePathMap = (data, parentPath = []) => {
const map = {};

data.forEach(node => {
const currentPath = [...parentPath, node.title];
map[node.key] = currentPath;

if (node.children) {
Object.assign(map, buildTitlePathMap(node.children, currentPath));
}
});

return map;
};


这样点击 'Current' 节点时就能拿到 ['Parent', 'Child', 'Current']

原理很简单:初始化时把整棵树拍平,每个 key 对应它的完整路径链,点击时直接查 Map,O(1) 复杂度,比每次都去遍历树快多了。
点赞
2026-03-19 21:03