Table of Contents
Requirements analysis
Function implementation
Recursive method
right mouse button menu
Add/modify/delete function
Search function
Tab reverse positioning
Drag and drop movement
End
Home Web Front-end Front-end Q&A Ant Design creates a tree component to implement editing, search and positioning functions

Ant Design creates a tree component to implement editing, search and positioning functions

Jan 13, 2022 pm 06:28 PM
ant design

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!

Ant Design creates a tree component to implement editing, search and positioning functions

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

Ant Design creates a tree component to implement editing, search and positioning functions

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';复制代码
Copy after login

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;
  });
};复制代码
Copy after login

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>
Copy after login

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;
}复制代码
Copy after login
  • 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>
  );复制代码
Copy after login

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;

Ant Design creates a tree component to implement editing, search and positioning functions

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:

Ant Design creates a tree component to implement editing, search and positioning functions

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:

Ant Design creates a tree component to implement editing, search and positioning functions

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.

Ant Design creates a tree component to implement editing, search and positioning functions

There is another need to filter the data source, which can be achieved by simply modifying the official instance;

Tab reverse positioning

Ant Design creates a tree component to implement editing, search and positioning functions

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.

Ant Design creates a tree component to implement editing, search and positioning functions

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:

Ant Design creates a tree component to implement editing, search and positioning functions

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

React's Role in HTML: Enhancing User Experience React's Role in HTML: Enhancing User Experience Apr 09, 2025 am 12:11 AM

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 and the Frontend: Building Interactive Experiences React and the Frontend: Building Interactive Experiences Apr 11, 2025 am 12:02 AM

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

What are the limitations of Vue 2's reactivity system with regard to array and object changes? What are the limitations of Vue 2's reactivity system with regard to array and object changes? Mar 25, 2025 pm 02:07 PM

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: Creating Reusable Elements in HTML React Components: Creating Reusable Elements in HTML Apr 08, 2025 pm 05:53 PM

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.

What are the benefits of using TypeScript with React? What are the benefits of using TypeScript with React? Mar 27, 2025 pm 05:43 PM

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

How can you use useReducer for complex state management? How can you use useReducer for complex state management? Mar 26, 2025 pm 06:29 PM

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 and the Frontend Stack: The Tools and Technologies React and the Frontend Stack: The Tools and Technologies Apr 10, 2025 am 09:34 AM

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.

What are functional components in Vue.js? When are they useful? What are functional components in Vue.js? When are they useful? Mar 25, 2025 pm 01:54 PM

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

See all articles