|
1 | | -import React, { memo, useEffect, useMemo, useState, createContext, useContext, useRef } from 'react'; |
| 1 | +import React, { memo, useEffect, useMemo, useState, createContext, useContext } from 'react'; |
2 | 2 | import styles from './index.less'; |
3 | 3 | import classnames from 'classnames'; |
4 | 4 | import Iconfont from '@/components/Iconfont'; |
@@ -48,6 +48,40 @@ const smoothTree = (treeData: ITreeNode[], result: ITreeNode[] = [], parentNode? |
48 | 48 | return result; |
49 | 49 | }; |
50 | 50 |
|
| 51 | +// 判断是否匹配 |
| 52 | +const isMatch = (target: string, searchValue: string) => { |
| 53 | + const reg = new RegExp(searchValue, 'i'); |
| 54 | + return reg.test(target || ''); |
| 55 | +}; |
| 56 | + |
| 57 | +// 树结构搜索 |
| 58 | +function searchTree(treeData: ITreeNode[], searchValue: string): ITreeNode[] { |
| 59 | + let result: ITreeNode[] = []; |
| 60 | + function dfs(node: ITreeNode, path: ITreeNode[] = []) { |
| 61 | + if (isMatch(node.name, searchValue)) { |
| 62 | + result = [...path, node]; |
| 63 | + return true; |
| 64 | + } |
| 65 | + if (!node.children) return false; |
| 66 | + for (const child of node.children) { |
| 67 | + if (dfs(child, [...path, node])) return true; |
| 68 | + } |
| 69 | + return false; |
| 70 | + } |
| 71 | + |
| 72 | + treeData.some((node) => dfs(node)); |
| 73 | + |
| 74 | + result.forEach((item) => { |
| 75 | + if(!isMatch(item.name, searchValue)){ |
| 76 | + item.children = null; |
| 77 | + } |
| 78 | + }); |
| 79 | + |
| 80 | + const smoothTreeList: ITreeNode[] = [] |
| 81 | + smoothTree(result, smoothTreeList); |
| 82 | + return smoothTreeList; |
| 83 | +} |
| 84 | + |
51 | 85 | const itemHeight = 26; // 每个 item 的高度 |
52 | 86 | const paddingCount = 2; |
53 | 87 |
|
@@ -89,17 +123,13 @@ const Tree = (props: IProps) => { |
89 | 123 | }, [smoothTreeData, searchTreeData, startIdx]); |
90 | 124 |
|
91 | 125 | useEffect(() => { |
92 | | - if (searchValue) { |
93 | | - const ls = smoothTreeData.filter((item) => { |
94 | | - const reg = new RegExp(searchValue, 'i'); |
95 | | - return reg.test(item.name || ''); |
96 | | - }); |
97 | | - setSearchTreeData(ls); |
| 126 | + if (searchValue && treeData) { |
| 127 | + setSearchTreeData(searchTree(cloneDeep(treeData), searchValue)); |
98 | 128 | } else { |
99 | 129 | setSearchTreeData(null); |
100 | 130 | } |
101 | 131 | setScrollTop(0); |
102 | | - }, [searchValue]); |
| 132 | + }, [searchValue, smoothTreeData]); |
103 | 133 |
|
104 | 134 | return ( |
105 | 135 | <LoadingContent isLoading={!treeData} className={classnames(className)}> |
|
0 commit comments