diff --git a/src/OptionList.tsx b/src/OptionList.tsx index fb8d3a8bd..ccb822192 100644 --- a/src/OptionList.tsx +++ b/src/OptionList.tsx @@ -1,4 +1,5 @@ import * as React from 'react'; +import { useEffect } from 'react'; import KeyCode from 'rc-util/lib/KeyCode'; import omit from 'rc-util/lib/omit'; import pickAttrs from 'rc-util/lib/pickAttrs'; @@ -140,12 +141,12 @@ const OptionList: React.ForwardRefRenderFunction< }; // Auto active first item when list length or searchValue changed - React.useEffect(() => { + useEffect(() => { setActive(defaultActiveFirstOption !== false ? getEnabledActiveIndex(0) : -1); }, [memoFlattenOptions.length, searchValue]); // Auto scroll to item position in single mode - React.useEffect(() => { + useEffect(() => { /** * React will skip `onChange` when component update. * `setActive` function will call root accessibility state update which makes re-render. @@ -157,8 +158,11 @@ const OptionList: React.ForwardRefRenderFunction< const index = memoFlattenOptions.findIndex( ({ data }) => (data as OptionData).value === value, ); - setActive(index); - scrollIntoView(index); + + if (index !== -1) { + setActive(index); + scrollIntoView(index); + } } }); @@ -168,7 +172,7 @@ const OptionList: React.ForwardRefRenderFunction< } return () => clearTimeout(timeoutId); - }, [open]); + }, [open, searchValue]); // ========================== Values ========================== const onSelectValue = (value: RawValueType) => { diff --git a/tests/Accessibility.test.tsx b/tests/Accessibility.test.tsx index 0bcf1e8f6..e2996f745 100644 --- a/tests/Accessibility.test.tsx +++ b/tests/Accessibility.test.tsx @@ -1,7 +1,8 @@ import { mount } from 'enzyme'; import * as React from 'react'; +import KeyCode from 'rc-util/lib/KeyCode'; import Select from '../src'; -import { injectRunAllTimers } from './utils/common'; +import { injectRunAllTimers, expectOpen } from './utils/common'; describe('Select.Accessibility', () => { injectRunAllTimers(jest); @@ -23,4 +24,49 @@ describe('Select.Accessibility', () => { }), ); }); + + // https://github.com/ant-design/ant-design/issues/31850 + it('active index should keep', () => { + const wrapper = mount( +