Skip to content

Commit 457562b

Browse files
committed
解决分组时排序失效问题
1 parent bbe6b41 commit 457562b

File tree

2 files changed

+54
-6
lines changed

2 files changed

+54
-6
lines changed

src/Select.tsx

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -431,15 +431,26 @@ const Select = React.forwardRef<BaseSelectRef, SelectProps<any, DefaultOptionTyp
431431
mergedSearchValue,
432432
mergedFieldNames,
433433
]);
434-
434+
const sorter = (options: DefaultOptionType[]) => {
435+
const sortedOptions = [...options].sort((a, b) =>
436+
filterSort(a, b, { searchValue: mergedSearchValue }),
437+
);
438+
const sortedOptionsWithNested = sortedOptions.map((item) => {
439+
if (Array.isArray(item.options)) {
440+
return {
441+
...item,
442+
options: sorter(item.options),
443+
};
444+
}
445+
return item;
446+
});
447+
return sortedOptionsWithNested;
448+
};
435449
const orderedFilteredOptions = React.useMemo(() => {
436450
if (!filterSort) {
437451
return filledSearchOptions;
438452
}
439-
440-
return [...filledSearchOptions].sort((a, b) =>
441-
filterSort(a, b, { searchValue: mergedSearchValue }),
442-
);
453+
return sorter(filledSearchOptions);
443454
}, [filledSearchOptions, filterSort, mergedSearchValue]);
444455

445456
const displayOptions = React.useMemo(

tests/Select.test.tsx

Lines changed: 38 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1947,7 +1947,44 @@ describe('Select.Basic', () => {
19471947
'Communicated',
19481948
);
19491949
});
1950-
1950+
it('filterSort should work with search value when grouping',() => {
1951+
const { container } = render(
1952+
<Select
1953+
open
1954+
showSearch
1955+
searchValue="entry"
1956+
style={{ width: 100 }}
1957+
placeholder="Search to Select"
1958+
optionFilterProp="label"
1959+
filterSort={
1960+
(optionA, optionB, info) => {
1961+
if (!info.searchValue) return 0;
1962+
const labelA = (optionA?.label ?? '').toLowerCase();
1963+
const labelB = (optionB?.label ?? '').toLowerCase();
1964+
const matchA = labelA.startsWith(info.searchValue);
1965+
const matchB = labelB.startsWith(info.searchValue);
1966+
if (matchA && !matchB) return -1;
1967+
if (!matchA && matchB) return 1;
1968+
return labelA.localeCompare(labelB);
1969+
}}
1970+
options={[
1971+
{
1972+
value: 'group1',
1973+
label: 'group1',
1974+
options: [
1975+
{ label: 'Entry1', value: 'Entry1' },
1976+
{ label: 'Entry2', value: 'Entry2' },
1977+
{ label: 'Entry3', value: 'Entry3' },
1978+
{ label: 'Entry', value: 'Entry' },
1979+
],
1980+
},
1981+
]}
1982+
/>,
1983+
);
1984+
expect(container.querySelector('.rc-select-item-option-grouped').textContent).toBe(
1985+
'Entry',
1986+
);
1987+
})
19511988
it('correctly handles the `tabIndex` prop', () => {
19521989
const { container } = render(<Select tabIndex={0} />);
19531990
expect(container.querySelector('.rc-select').getAttribute('tabindex')).toBeFalsy();

0 commit comments

Comments
 (0)