Skip to content

Commit d21b6bb

Browse files
MadCccyoyo837
andauthored
fix: fix menu item focus (#680)
* chore: test * fix: fix focus --------- Co-authored-by: tanghui <[email protected]>
1 parent 67baccb commit d21b6bb

File tree

3 files changed

+13
-3
lines changed

3 files changed

+13
-3
lines changed

docs/examples/debug.tsx

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
/* eslint no-console:0 */
22

3-
import React from 'react';
3+
import React, { useRef } from 'react';
44
import type { CSSMotionProps } from 'rc-motion';
5-
import Menu, { ItemGroup as MenuItemGroup } from '../../src';
5+
import Menu, { ItemGroup as MenuItemGroup, MenuItem } from '../../src';
66
import type { MenuProps } from '../../src';
77
import '../../assets/index.less';
88
import '../../assets/menu.less';
@@ -52,6 +52,7 @@ export default () => {
5252
const [inlineCollapsed, setInlineCollapsed] = React.useState(false);
5353
const [forceRender, setForceRender] = React.useState(false);
5454
const [openKeys, setOpenKeys] = React.useState<string[]>([]);
55+
const menuRef = useRef();
5556

5657
const onRootClick = (info: MenuInfo) => {
5758
console.log('Root Menu Item Click:', info);
@@ -68,6 +69,10 @@ export default () => {
6869
return (
6970
<>
7071
<div>
72+
<Menu ref={menuRef}>
73+
<MenuItem key="light">Light</MenuItem>
74+
</Menu>
75+
<button onClick={() => menuRef.current.focus()}>focus</button>
7176
<select value={mode} onChange={e => setMode(e.target.value as any)}>
7277
<option value="inline">Inline</option>
7378
<option value="vertical">Vertical</option>

src/Menu.tsx

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -397,7 +397,10 @@ const Menu = React.forwardRef<MenuRef, MenuProps>((props, ref) => {
397397
);
398398

399399
const shouldFocusKey =
400-
mergedActiveKey ?? element2key.get(focusableElements[0]);
400+
mergedActiveKey ??
401+
(focusableElements[0]
402+
? element2key.get(focusableElements[0])
403+
: childList.find(node => !node.props.disabled)?.key);
401404

402405
const elementToFocus = key2element.get(shouldFocusKey);
403406

tests/Menu.spec.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -701,6 +701,8 @@ describe('Menu', () => {
701701
);
702702

703703
expect(menuRef.current?.list).toBe(container.querySelector('ul'));
704+
act(() => menuRef.current.focus());
705+
expect(document.activeElement).toBe(container.querySelector('li'));
704706
});
705707

706708
it('should render a divider with role="separator"', () => {

0 commit comments

Comments
 (0)