fix(dropdown): Dropdown menu support transmit ref (#43002)

* fix(dropdown): Dropdown menu support transmit ref

* chore: add test case
This commit is contained in:
JiaQi 2023-06-18 13:21:39 +08:00 committed by GitHub
parent 446e8336dc
commit 8cdb76bad6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 26 additions and 8 deletions

View File

@ -1,7 +1,7 @@
import React from 'react';
import mountTest from '../../../tests/shared/mountTest';
import rtlTest from '../../../tests/shared/rtlTest';
import { render } from '../../../tests/utils';
import { render, waitFakeTimer } from '../../../tests/utils';
import type { DropdownProps } from '../dropdown';
import DropdownButton from '../dropdown-button';
@ -156,4 +156,17 @@ describe('DropdownButton', () => {
render(<DropdownButton open dropdownRender={dropdownRender} />);
expect(dropdownRender).toHaveBeenCalled();
});
it('should support focus menu when set autoFocus', async () => {
jest.useFakeTimers();
const items = [
{
label: 'foo',
key: '1',
},
];
const { container } = render(<DropdownButton open autoFocus menu={{ items }} />);
await waitFakeTimer();
expect(container.querySelector('.ant-dropdown-menu-item-active')).toBeTruthy();
});
});

View File

@ -14,7 +14,6 @@ import { ConfigContext } from '../config-provider';
import type { MenuProps } from '../menu';
import Menu from '../menu';
import { OverrideProvider } from '../menu/OverrideContext';
import { NoCompactStyle } from '../space/Compact';
import theme from '../theme';
import useStyle from './style';
@ -274,7 +273,7 @@ const Dropdown: CompoundedComponent = (props) => {
);
}}
>
<NoCompactStyle>{overlayNode}</NoCompactStyle>
{overlayNode}
</OverrideProvider>
);
};

View File

@ -1,4 +1,5 @@
import * as React from 'react';
import { NoCompactStyle } from '../space/Compact';
import type { MenuProps } from './menu';
// Used for Dropdown only
@ -14,9 +15,10 @@ export interface OverrideContextProps {
const OverrideContext = React.createContext<OverrideContextProps | null>(null);
/** @internal Only used for Dropdown component. Do not use this in your production. */
export const OverrideProvider: React.FC<OverrideContextProps & { children: React.ReactNode }> = (
props,
) => {
export const OverrideProvider = React.forwardRef<
HTMLElement,
OverrideContextProps & { children: React.ReactNode }
>((props, ref) => {
const { children, ...restProps } = props;
const override = React.useContext(OverrideContext);
@ -32,8 +34,12 @@ export const OverrideProvider: React.FC<OverrideContextProps & { children: React
],
);
return <OverrideContext.Provider value={context}>{children}</OverrideContext.Provider>;
};
return (
<OverrideContext.Provider value={context}>
<NoCompactStyle>{React.cloneElement(children as React.ReactElement, { ref })}</NoCompactStyle>
</OverrideContext.Provider>
);
});
/** @internal Only used for Dropdown component. Do not use this in your production. */
export default OverrideContext;