1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
| import { Tree } from 'antd' import { DataNode, TreeProps } from 'antd/lib/tree' import { useState } from 'react'
const AntdTree = () => { const [treeData, setTreeData] = useState<DataNode[]>([ { title: 'A', key: 'A', children: [ { title: 'A-1', key: 'A-1', children: [ { title: 'A-1-1', key: 'A-1-1' } ] }, { title: 'A-2', key: 'A-2' }, { title: 'A-3', key: 'A-3' }, { title: 'A-4', key: 'A-4' } ] }, { title: 'B', key: 'B', children: [ { title: 'B-1', key: 'B-1' }, { title: 'B-2', key: 'B-2' } ] } ])
const handleDrop: TreeProps['onDrop'] = (info) => { const dragKey = info.dragNode.key const dropKey = info.node.key const dropPos = info.node.pos.split('-') const realDropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]) const isDropToGap = info.dropToGap
const searchNode = ( data: DataNode[], key: React.Key, callback: (nodeData: DataNode, nodeIndex: number, nodeArray: DataNode[]) => void ) => { for (let i = 0; i < data.length; i++) { const isMatchKey = data[i].key === key if (isMatchKey) { return callback(data[i], i, data) } if (data[i].children) { searchNode(data[i].children!, key, callback) } } }
const newTreeData = JSON.parse(JSON.stringify(treeData))
let dragObj: DataNode
searchNode(newTreeData, dragKey, (nodeData, nodeIndex, nodeArray) => { nodeArray.splice(nodeIndex, 1) dragObj = nodeData console.log('dragObj', dragObj) })
if (!isDropToGap) { searchNode(newTreeData, dropKey, (nodeData) => { nodeData.children = nodeData.children || [] nodeData.children.unshift(dragObj) }) } else { searchNode(newTreeData, dropKey, (nodeData, nodeIndex, nodeArray) => { console.log('nodeArray', nodeArray) console.log('dropDataIndex', nodeIndex) if (realDropPosition === -1) { nodeArray.splice(nodeIndex, 0, dragObj) } else { nodeArray.splice(nodeIndex + 1, 0, dragObj) } }) }
setTreeData(newTreeData) }
return ( <div> <Tree treeData={treeData} selectable={false} onDrop={handleDrop} draggable blockNode /> </div> ) }
export default AntdTree
|