Skip to content

Commit 18f48cd

Browse files
committed
feat(SelectInput): optimize width calculation logic
1 parent 9b1fcb0 commit 18f48cd

File tree

1 file changed

+18
-9
lines changed

1 file changed

+18
-9
lines changed

packages/components/select-input/useOverlayInnerStyle.ts

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@ export default function useOverlayInnerStyle(
3030
const { popupProps, autoWidth, readonly, disabled, onPopupVisibleChange, allowInput } = props;
3131
const [innerPopupVisible, setInnerPopupVisible] = useControlled(props, 'popupVisible', onPopupVisibleChange);
3232

33+
const contentWidthRef = useRef<number | null>(null);
3334
const skipNextBlur = useRef(false);
3435

3536
const matchWidthFunc = (triggerElement: HTMLElement, popupElement: HTMLElement) => {
@@ -39,21 +40,28 @@ export default function useOverlayInnerStyle(
3940
// 设置display来可以获取popupElement的宽度
4041
// eslint-disable-next-line no-param-reassign
4142
popupElement.style.display = '';
43+
44+
/**
45+
* https://github.com/Tencent/tdesign-react/issues/3858
46+
* 记录内容宽度,避免 resize 过程中经过分支临界点时,将宽度锁死
47+
* 无法在 popup 和 trigger 宽度两个分支间正确切换
48+
*/
49+
if (contentWidthRef.current === null) {
50+
contentWidthRef.current = popupElement.scrollWidth;
51+
}
4252
// popupElement的scrollBar宽度
4353
const overlayScrollWidth = popupElement.offsetWidth - popupElement.scrollWidth;
4454

4555
/**
46-
* issue:https://github.com/Tencent/tdesign-react/issues/2642
47-
*
48-
* popupElement的内容宽度不超过triggerElement的宽度,就使用triggerElement的宽度减去popup的滚动条宽度,
49-
* 让popupElement的宽度加上scrollBar的宽度等于triggerElement的宽度;
50-
*
51-
* popupElement的内容宽度超过triggerElement的宽度,就使用popupElement的scrollWidth,
52-
* 不用offsetWidth是会包含scrollBar的宽度
56+
* https://github.com/Tencent/tdesign-react/issues/2642
57+
* 取 popup 和 trigger 元素宽度的较大值进行比较
58+
* 如果 popup ≤ trigger,使用 trigger 宽度减去 popup 滚动条宽度
59+
* 否则,使用 popup 的 scrollWidth
60+
* 不用 offsetWidth,因为它会包含滚动条的宽度
5361
*/
5462
const width =
55-
popupElement.offsetWidth - overlayScrollWidth > triggerElement.offsetWidth
56-
? popupElement.scrollWidth
63+
contentWidthRef.current > triggerElement.offsetWidth
64+
? contentWidthRef.current
5765
: triggerElement.offsetWidth - overlayScrollWidth;
5866

5967
if (prevDisplay === 'none') {
@@ -80,6 +88,7 @@ export default function useOverlayInnerStyle(
8088
if (!newVisible) {
8189
extra?.afterHidePopup?.(context);
8290
skipNextBlur.current = true;
91+
contentWidthRef.current = null;
8392
}
8493
}
8594
};

0 commit comments

Comments
 (0)