You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从react-arborist树形组件中获取排序后的数据

如何从react-arborist获取拖拽排序后的树形数据?

react-arborist 内置了直接获取更新后数据的方法,主要通过两种方式实现:

1. 监听结构变化自动获取(推荐)

利用 Tree 组件的 onChange 回调,每次拖拽排序或树结构变更时,回调会接收当前的 tree 实例,调用其 getData() 方法即可拿到排序后的完整树形数据:

import { Tree } from 'react-arborist';

// 示例初始数据(支持嵌套children或扁平parentId结构)
const initialData = [
  { id: '1', name: '节点1', children: [{ id: '1-1', name: '子节点1' }] },
  { id: '2', name: '节点2' }
];

function SortableTree() {
  const handleTreeChange = (tree) => {
    // 获取排序后的完整数据,结构与传入的initialData完全一致
    const sortedTreeData = tree.getData();
    // 可将数据存入状态、发送后端或做其他处理
    console.log('排序后的数据:', sortedTreeData);
  };

  return (
    <Tree
      items={initialData}
      onChange={handleTreeChange}
      draggable // 开启拖拽功能
      canDrop={() => true} // 允许所有节点拖拽放置
    >
      {({ node }) => (
        <div style={{ paddingLeft: `${node.depth * 20}px` }}>
          {node.data.name}
        </div>
      )}
    </Tree>
  );
}

2. 主动触发获取(比如点击按钮时)

通过 useTree 钩子获取 tree 实例,在需要的时机(如按钮点击)调用 getData() 获取当前排序后的数据:

import { Tree, useTree } from 'react-arborist';

function SortableTree() {
  const tree = useTree();

  const handleGetSortedData = () => {
    if (!tree) return;
    const sortedTreeData = tree.getData();
    console.log('当前排序后的数据:', sortedTreeData);
  };

  return (
    <>
      <button onClick={handleGetSortedData}>获取排序后的数据</button>
      <Tree
        items={initialData}
        draggable
        canDrop={() => true}
      >
        {({ node }) => (
          <div style={{ paddingLeft: `${node.depth * 20}px` }}>
            {node.data.name}
          </div>
        )}
      </Tree>
    </>
  );
}

注意事项

  • getData() 返回的数据结构与你传入 Tree 组件的 items 结构完全一致:如果是嵌套 children 结构,返回嵌套树形;如果是扁平结构(带 parentId),返回排序后的扁平数组。
  • 无需手动处理拖拽后的层级或顺序,tree.getData() 已经自动同步了所有变更。

内容的提问来源于stack exchange,提问作者Merger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 06:24:54