Home  >  Article  >  Web Front-end  >  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

青灯夜游
青灯夜游forward
2022-01-13 18:28:214236browse

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

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;

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:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete