Skip to content

Commit 5158f82

Browse files
jin19980928WB01676250
and
WB01676250
authored
Feat:Add FindItem With MenuRef (#759)
* feat: menuRef * feat: menuRef * feat: menuRef * feat:menuRef * feat:menuRef --------- Co-authored-by: WB01676250 <jl01676250@antgroup.com>
1 parent eda49a3 commit 5158f82

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

src/Menu.tsx

+5
Original file line numberDiff line numberDiff line change
@@ -426,6 +426,11 @@ const Menu = React.forwardRef<MenuRef, MenuProps>((props, ref) => {
426426
elementToFocus?.focus?.(options);
427427
}
428428
},
429+
findItem: ({ key: itemKey }) => {
430+
const keys = getKeys();
431+
const { key2element } = refreshElements(keys, uuid);
432+
return key2element.get(itemKey) || null;
433+
},
429434
};
430435
});
431436

src/interface.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -134,9 +134,12 @@ export type MenuRef = {
134134
*/
135135
focus: (options?: FocusOptions) => void;
136136
list: HTMLUListElement;
137+
findItem: (params: { key: string }) => HTMLElement | null;
137138
};
138139

139140
// ======================== Component ========================
140141
export type ComponentType = 'submenu' | 'item' | 'group' | 'divider';
141142

142-
export type Components = Partial<Record<ComponentType, React.ComponentType<any>>>;
143+
export type Components = Partial<
144+
Record<ComponentType, React.ComponentType<any>>
145+
>;

tests/Menu.spec.tsx

+18
Original file line numberDiff line numberDiff line change
@@ -807,5 +807,23 @@ describe('Menu', () => {
807807
rerender(<App expand={false} subExpand />);
808808
expect(container.querySelectorAll('.rc-menu-submenu-arrow').length).toBe(1);
809809
});
810+
811+
it('should find item by key', () => {
812+
const menuRef = React.createRef<MenuRef>();
813+
const { container } = render(
814+
<Menu ref={menuRef}>
815+
<MenuItem key="light">Light</MenuItem>
816+
<MenuItem key="cat">Cat</MenuItem>
817+
</Menu>,
818+
);
819+
820+
const lightItem = menuRef.current?.findItem({ key: 'light' });
821+
const catItem = menuRef.current?.findItem({ key: 'cat' });
822+
const nonExistentItem = menuRef.current?.findItem({ key: 'dog' });
823+
824+
expect(lightItem).toBe(container.querySelectorAll('li')[0]);
825+
expect(catItem).toBe(container.querySelectorAll('li')[1]);
826+
expect(nonExistentItem).toBe(null);
827+
});
810828
});
811829
/* eslint-enable */

0 commit comments

Comments
 (0)