Skip to content

Commit 8a736b6

Browse files
committed
fix(select): initially scroll to the active item in OptionGroup
fix #3135
1 parent 7e0bd73 commit 8a736b6

File tree

2 files changed

+25
-3
lines changed

2 files changed

+25
-3
lines changed

src/_util/helper.ts

+17
Original file line numberDiff line numberDiff line change
@@ -71,3 +71,20 @@ export function getPropsApiByEvent(eventName: string) {
7171
export function pxCompat(param: string | number) {
7272
return typeof param === 'number' ? `${param}px` : param;
7373
}
74+
75+
/**
76+
* 获取元素相对于容器(祖先)的偏移量
77+
* @param element 目标元素
78+
* @param container 容器元素
79+
* @returns 相对于容器的偏移量
80+
*/
81+
export function getOffsetTopToContainer(element: HTMLElement, container: HTMLElement) {
82+
let { offsetTop } = element;
83+
84+
let current = element.offsetParent as HTMLElement;
85+
while (current && current !== container) {
86+
offsetTop += current.offsetTop;
87+
current = current.offsetParent as HTMLElement;
88+
}
89+
return offsetTop;
90+
}

src/select/base/Select.tsx

+8-3
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import classNames from 'classnames';
1414
import isFunction from 'lodash/isFunction';
1515
import get from 'lodash/get';
1616
import debounce from 'lodash/debounce';
17+
import { getOffsetTopToContainer } from 'tdesign-react/_util/helper';
1718
import useControlled from '../../hooks/useControlled';
1819
import { useLocaleReceiver } from '../../locale/LocalReceiver';
1920
import useConfig from '../../hooks/useConfig';
@@ -385,12 +386,16 @@ const Select = forwardRefWithStatics(
385386
const elementBottomHeight = parseInt(paddingBottom, 10) + parseInt(marginBottom, 10);
386387
// 小于0时不需要特殊处理,会被设为0
387388
const updateValue =
388-
firstSelectedNode.offsetTop -
389+
getOffsetTopToContainer(firstSelectedNode, content) -
389390
content.offsetTop -
390391
(content.clientHeight - firstSelectedNode.clientHeight) +
391392
elementBottomHeight;
392-
// eslint-disable-next-line no-param-reassign
393-
content.scrollTop = updateValue;
393+
394+
// 通过 setTimeout 确保组件渲染完成后再设置 scrollTop
395+
setTimeout(() => {
396+
// eslint-disable-next-line no-param-reassign
397+
content.scrollTop = updateValue;
398+
});
394399
}
395400
};
396401

0 commit comments

Comments
 (0)