Skip to content

Commit e52f1fa

Browse files
authored
feat: support ref (#435)
* feat: support ref * test: fix test case
1 parent 7b56f09 commit e52f1fa

File tree

3 files changed

+18
-4
lines changed

3 files changed

+18
-4
lines changed

src/Menu.tsx

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import { PathRegisterContext, PathUserContext } from './context/PathContext';
2727
import useKeyRecords, { OVERFLOW_KEY } from './hooks/useKeyRecords';
2828
import { IdContext } from './context/IdContext';
2929
import PrivateContext from './context/PrivateContext';
30+
import { composeRef } from 'rc-util/lib/ref';
3031

3132
/**
3233
* Menu modify after refactor:
@@ -145,7 +146,7 @@ interface LegacyMenuProps extends MenuProps {
145146
openAnimation?: string;
146147
}
147148

148-
const Menu: React.FC<MenuProps> = props => {
149+
const Menu = React.forwardRef<HTMLUListElement, MenuProps>((props, ref) => {
149150
const {
150151
prefixCls = 'rc-menu',
151152
style,
@@ -223,6 +224,7 @@ const Menu: React.FC<MenuProps> = props => {
223224
const [mounted, setMounted] = React.useState(false);
224225

225226
const containerRef = React.useRef<HTMLUListElement>();
227+
const mergedRef = composeRef(containerRef, ref);
226228

227229
const uuid = useUUID(id);
228230

@@ -488,7 +490,7 @@ const Menu: React.FC<MenuProps> = props => {
488490
const container = (
489491
<Overflow
490492
id={id}
491-
ref={containerRef as any}
493+
ref={mergedRef as any}
492494
prefixCls={`${prefixCls}-overflow`}
493495
component="ul"
494496
itemComponent={MenuItem}
@@ -591,6 +593,6 @@ const Menu: React.FC<MenuProps> = props => {
591593
</IdContext.Provider>
592594
</PrivateContext.Provider>
593595
);
594-
};
596+
});
595597

596598
export default Menu;

tests/Menu.spec.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -647,5 +647,17 @@ describe('Menu', () => {
647647
jest.useRealTimers();
648648
});
649649
});
650+
651+
it('should support ref', () => {
652+
const menuRef = React.createRef();
653+
654+
mount(
655+
<Menu ref={menuRef}>
656+
<MenuItem key="light">Light</MenuItem>
657+
</Menu>,
658+
);
659+
660+
expect(menuRef.current).toBeTruthy();
661+
});
650662
});
651663
/* eslint-enable */

tests/SubMenu.spec.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -366,7 +366,7 @@ describe('SubMenu', () => {
366366
);
367367

368368
const wrapper = mount(<App show />);
369-
expect(wrapper.find('Menu ul').prop('style')).toEqual({
369+
expect(wrapper.find('.rc-menu').first().prop('style')).toEqual({
370370
backgroundColor: 'black',
371371
});
372372
});

0 commit comments

Comments
 (0)