import { useCallback } from "react"; const SCROLL_OFFSET = 0; const SCROLL_DURATION = 100; /** * 滚动到指定元素 */ function scrollToElement( element: HTMLElement, to: number, duration: number ): void { if (duration <= 0) { element.scrollTop = to; return; } const difference = to - element.scrollTop; const perTick = (difference / duration) * 10; requestAnimationFrame(() => { element.scrollTop += perTick; if (element.scrollTop === to) return; scrollToElement(element, to, duration - 10); }); } export function useListScroll(selectRef) { /** * 滚动到当前选择元素 */ const scrollTo = useCallback( ( index: number, offset: number = SCROLL_OFFSET, duration: number = SCROLL_DURATION ) => { const element = selectRef.current; if (!element) { return; } const topOption = element.children[index] as HTMLElement; if (!topOption) { return; } const to = topOption.offsetTop - element.offsetTop - offset; scrollToElement(element, to, duration); }, [selectRef] ); return scrollTo; }