import { Tree } from '@btri-ui/base'; import type { DataNode, TreeProps } from 'antd/es/tree'; import React, { useState } from 'react'; const treeData = [ { title: '第一层1', key: '1', children: [ { title: '第二层1', key: '1-1', children: [ { title: '第三层1', key: '1-1-1', }, { title: '第三层2', key: '1-1-2', }, ], }, { title: '第二层2', key: '1-2', children: [ { title: '第三层1', key: '1-2-1', }, { title: '第三层2', key: '1-2-2', }, ], }, ], }, { title: '第一层2', key: '2', children: [ { title: '第二层1', key: '2-1', children: [ { title: '第三层1', key: '2-1-1', }, { title: '第三层2', key: '2-1-2', }, ], }, { title: '第二层', key: '2-2', children: [ { title: '第三层1', key: '2-2-1', }, { title: '第三层2', key: '2-2-2', }, ], }, ], }, ]; const App = () => { const [gData, setGData] = React.useState(treeData); const onSelect = (selectedKeys, info) => { console.log('selected', selectedKeys, info); }; const onCheck = (checkedKeys, info) => { console.log('onCheck', checkedKeys, info); }; const onDragEnter: TreeProps['onDragEnter'] = (info) => { console.log(info); // expandedKeys 需要受控时设置 // setExpandedKeys(info.expandedKeys) }; const onDrop: TreeProps['onDrop'] = (info) => { console.log(info); const dropKey = info.node.key; const dragKey = info.dragNode.key; const dropPos = info.node.pos.split('-'); const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]); const loop = ( data: DataNode[], key: React.Key, callback: (node: DataNode, i: number, data: DataNode[]) => void, ) => { for (let i = 0; i < data.length; i++) { if (data[i].key === key) { return callback(data[i], i, data); } if (data[i].children) { loop(data[i].children!, key, callback); } } }; const data = [...treeData]; // Find dragObject let dragObj: DataNode; loop(data, dragKey, (item, index, arr) => { arr.splice(index, 1); dragObj = item; }); if (!info.dropToGap) { // Drop on the content loop(data, dropKey, (item) => { item.children = item.children || []; // where to insert 示例添加到头部,可以是随意位置 item.children.unshift(dragObj); }); } else if ( ((info.node as any).props.children || []).length > 0 && // Has children (info.node as any).props.expanded && // Is expanded dropPosition === 1 // On the bottom gap ) { loop(data, dropKey, (item) => { item.children = item.children || []; // where to insert 示例添加到头部,可以是随意位置 item.children.unshift(dragObj); // in previous version, we use item.children.push(dragObj) to insert the // item to the tail of the children }); } else { let ar: DataNode[] = []; let i: number; loop(data, dropKey, (_item, index, arr) => { ar = arr; i = index; }); if (dropPosition === -1) { ar.splice(i!, 0, dragObj!); } else { ar.splice(i! + 1, 0, dragObj!); } } setGData(data); }; return ( ); }; export default App;