首页 > 解决方案 > useRef、useLayoutEffect、Element.scrollTo 每次都不工作

问题描述

我有一张带刷新功能的桌子。我希望能够在刷新时保持用户在表中的位置。现在这将在大多数情况下工作,但偶尔它会滚动回元素的顶部。

常量 scrollYRef = useRef(0); const tableRef = useRef<HTMLDivElement | 空>(空);

const handleScroll = (): void => {
    if (!!tableRef.current) {
        tableRef.current.addEventListener("scroll", (e: Event): void => {
            if (!!tableRef.current && tableRef.current !== null) {
                if ((e.target as HTMLDivElement).scrollTop || scrollYRef.current === 1) {
                    scrollYRef.current = (e.target as HTMLDivElement).scrollTop;
                }
            }
        });
    }
};

useEffect(handleScroll, []);

useEffect(() => {
    const current = tableRef.current;
    if (!!current) {
        if (current.scrollTop === 0 && scrollYRef.current > 100 && pagedEmployeeInfo.length) {
            requestAnimationFrame(() => {
                if (current) {
                    current.scrollTo({ left: current.scrollLeft, top: scrollYRef.current });
                }
            });
        }
    }
}, [pagedEmployeeInfo]);

标签: use-ref

解决方案


推荐阅读