


Ant Design creates a tree component to implement editing, search and positioning functions
How to customize the Ant Design tree component to implement editing, search and reverse positioning functions? The following article will introduce to you how to create tree components and implement these functions. I hope it will be helpful to you!
This time I made a tree-shaped display function. Who knows that the product is still unfinished, so he came to talk to me:
PD: What? Only expand and collapse function? How can this work? Our most basic thing is to support editing and search. If possible, we can also do reverse positioning...
YY: Why didn't you tell me earlier? It’s not even in the requirements document...
#PD: Whose document do you think was written right in one go? Which PD does not add requirements?
YY: That's what they say, but that's not how things work...
PD: Oh, don't waste your time. , do it quickly!
YY: ...
The above stories are purely fictitious. If there are any similarities, please leave a message in the comment area...
Tree shape Data is relatively common in development, such as folders, organizational structures, biological classifications, countries and regions, etc. Most of the structures in the world are tree structures. The tree control can fully display the hierarchical relationship, and has interactive functions such as expansion and collapse selection.
Requirements analysis
- Edit: add/modify/delete/move
- Search function: name/creator/owner filter
- Positioning: tab reverse positioning
Project warehouse: https://github.com/speakice/editable-tree
Function implementation
There are many method libraries and components that can realize the above functions. Here we only talk about one of them, which are all components of Ant Design:
- Tree.DirectoryTree directory tree
- Dropdown Right-click menu container
- Menu Menu content
- Tabs Right Tab page
- Input.Search Search box
- Switch Switch association status
- shortid generates a unique id
import { Tree, Dropdown, Menu, Tabs, Input, Switch } from 'antd';import shortid from 'shortid';复制代码
Recursive method
To operate tree row data, the most important prerequisite is to have a handy recursive method:
/** * 如果需要修改tree,action就返回修改后的item, 不修改就不返回 */export const deepTree = (tree = [], action = () => {}) => { return tree.map((item) => { const newItem = action({ ...item }) || item; if (newItem.children) { newItem.children = deepTree(newItem.children, action); } return newItem; }); };复制代码
right mouse button menu
The right-click menu works on the title, and Dropdown needs to be written to the data source of the tree component:
<directorytree> setRightClickKey(node.key)} onSelect={onSelect} selectedKeys={rightConnect ? [activeTabKey] : selectedKeys} onExpand={onExpand} treeData={[ ...deepTree(treeData, (item) => { return { ...item, titleWord: item.title, title: ( <dropdown> setRightClickKey()} overlayStyle={{ width: 80 }} overlay={menu(item)} > <div> {item.title} </div> </dropdown> ), }; }), ]} />复制代码</directorytree>
There are a few points that need to be added about the right-click menu:
- The trigger attribute of Dropdown needs to be set to contextMenu;
- The position displayed by Dropdown is relative to the title, and the width of the outer container needs to be set to cover the remaining space:
.ant-tree-node-content-wrapper { display: flex; }.ant-tree-title { flex: 1; }复制代码
- The display of Dropdown is judged by right-clicking the key of the record;
- The menu of Dropdown needs to pass the current item;
const menu = (node) => ( <menu> { domEvent.stopPropagation(); console.log('menuClick', node, key); // 如果要添加操作顶层文件夹,可以直接操作 switch (key) { case 'add': setTreeData( deepTree(treeData, (item) => { if (item.children && item.key === node.key) { return { ...item, children: [ ...item.children, { title: 'new add', key: shortid.generate(), isLeaf: true, }, ], }; } }) ); break; case 'delete': const outer = treeData.find((item) => item.key === node.key); if (outer) { setTreeData(treeData.filter((item) => item.key !== node.key)); return; } setTreeData( deepTree(treeData, (item) => { if (item.children) { return { ...item, children: item.children.filter( ({ key }) => key !== node.key ), }; } return item; }) ); break; case 'edit': setTreeData( deepTree(treeData, (item) => { if (item.key === node.key) { console.log('editle', { ...item, title: 'new edit', }); return { ...item, title: 'new edit', }; } return item; }) ); break; } }} > <menu.item>新增</menu.item> <menu.item> 删除 </menu.item> <menu.item>编辑</menu.item> </menu> );复制代码
Add/modify/delete function
The adding function can only be added to the folder by default, and the addition is judged by the key value. The processing here is relatively simple, only the core function demonstration is done, the code is shown in the previous section;
The modification function has also been given a simple example. In formal projects, it is generally necessary to pop-up window editing or embed an input box in the title of the tree component. You can use variables to record the item being edited, and finally save it and insert it into the tree data recursively. Medium:
The deletion function has been judged. If it is to delete the outermost layer, it will be filtered directly through the filter. ⚠️OtherwiseThe deletion function is filtered by children, special attention should be paid here.
Search function
The search function is prompted by the titile color turning red:
The implementation is only after clicking the search Search, there is no real-time search prompt, and there is no search word distinction. Here you can intercept the string to implement it. You can see Official Example, Note that the attribute autoExpandParent of the parent node is opened by default. , otherwise it may take some effort to recurse upward.
There is another need to filter the data source, which can be achieved by simply modifying the official instance;
Tab reverse positioning
Click on the Tree component item, add Tab on the right, or activate Tab, which can be regarded as forward positioning; reverse positioning means that when the Tab page on the right is switched, the Tree component on the left selects the corresponding item, and the core code is specified selectedKeys is not difficult in comparison. The difficulty lies in opening the relevant parent node by default. Of course, as mentioned before, it is good to control the autoExpandParent attribute.
Drag and drop movement
Drag and drop movement is supported by the Tree component itself, and secondly, the official has given drag and drop movement examples, I only slightly modified the official example, so I won’t go into details here:
End
The difficulty of search and reverse positioning is actually When opening the associated folder, the autoExpandParent attribute is used in the official example, which makes it much simpler.
It’s not too early, we’re here today.
For more programming related knowledge, please visit: Programming Video! !
The above is the detailed content of Ant Design creates a tree component to implement editing, search and positioning functions. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

Vue 2's reactivity system struggles with direct array index setting, length modification, and object property addition/deletion. Developers can use Vue's mutation methods and Vue.set() to ensure reactivity.

React components can be defined by functions or classes, encapsulating UI logic and accepting input data through props. 1) Define components: Use functions or classes to return React elements. 2) Rendering component: React calls render method or executes function component. 3) Multiplexing components: pass data through props to build a complex UI. The lifecycle approach of components allows logic to be executed at different stages, improving development efficiency and code maintainability.

TypeScript enhances React development by providing type safety, improving code quality, and offering better IDE support, thus reducing errors and improving maintainability.

The article explains using useReducer for complex state management in React, detailing its benefits over useState and how to integrate it with useEffect for side effects.

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

Functional components in Vue.js are stateless, lightweight, and lack lifecycle hooks, ideal for rendering pure data and optimizing performance. They differ from stateful components by not having state or reactivity, using render functions directly, a
