irychen / keepalive-for-react

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

How to restore the scrollbar to its previous position #17

Closed escfex closed 3 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

感谢

Muhammad-96 commented 3 days ago

@irychen Scrolling does not occur. Does this solution work for you? I assume that scrolling occurs until the component appears in the DOM

irychen commented 3 days ago

@irychen Scrolling does not occur. Does this solution work for you? I assume that scrolling occurs until the component appears in the DOM

you need extra hook like above or just use the MemoScrollTopWrapper component https://stackblitz.com/github/irychen/keepalive-for-react/tree/main/examples/react-router-dom-simple-starter?file=src%2Flayout%2Findex.tsx