irychen / keepalive-for-react

React KeepAlive is a component that can cache the state of the component and reuse it when needed.
MIT License
187 stars 34 forks source link

How to restore the scrollbar to its previous position #17

Closed escfex closed 2 months ago

irychen commented 3 months ago
export function useScrollMemo(containerRef: RefObject<HTMLDivElement>) {
    const historyScrollTop = useRef(0)
    const { active } = useKeepAliveContext()

    useEffect(() => {
        if (active) {
            containerRef.current?.scrollTo(0, historyScrollTop.current)
        }
    }, [active])

    useEffect(() => {
        const divDom = containerRef.current
        if (!divDom) return
        const onScroll = (e: Event) => {
            const target = e.target as HTMLDivElement
            if (!target) return
            historyScrollTop.current = target?.scrollTop || 0
        }
        divDom?.addEventListener("scroll", onScroll)
        return () => {
            divDom?.removeEventListener("scroll", onScroll)
        }
    }, [])
}

参考一下

escfex commented 3 months ago

感谢