簡體   English   中英

如何在路線更改后滾動到頁面頂部,但返回時保留滾動 position?

[英]How to scroll to the top of the page after a route change, but retain the scroll position when going back?

我想在更改路線后滾動到頁面頂部。 但是,當用戶在瀏覽器中按下“返回”按鈕時,我希望他們返回上一頁上的上一個滾動 position 而不是頂部。 我已經實現了 n“滾動到頂部”功能並且它有效( 鏈接)。 但是,我想知道在“返回”時如何修改它以記住以前的滾動 position。

滾動到頂部:

import React, { useEffect, Fragment } from "react";
import { withRouter } from "react-router-dom";

function ScrollToTop({ history, children }) {
  useEffect(() => {
    const unlisten = history.listen(() => {
      window.scrollTo(0, 0);
    });
    return () => {
      unlisten();
    };
  }, []);

  return <Fragment>{children}</Fragment>;
}

export default withRouter(ScrollToTop);

應用程序.js

<ScrollToTop>
   <Switch>
       <PublicRoute exact path="/join/" component={LandingPage} />
   </Switch>
</ScrollToTop>

實現此目的的一種方法是通過位置鍵和 window x、y 坐標跟蹤用戶的位置。 react-router-dom 在這里給出了一個好主意。

這是一個可能看起來像的示例。

export default function ScrollRestoration() {
  const { key } = useLocation();
  const positions = useRef(new Map());

  useEffect(() => {
    if (positions.current.has(key)) {
      const { x, y } = positions.current.get(key);
      window.scrollTo(x, y);
    } else {
      window.scrollTo(0, 0);
    }

    const handler = () => {
      positions.current.set(key, { x: window.scrollX, y: window.scrollY });
    };

    window.addEventListener("scroll", handler);
    return () => {
      window.removeEventListener("scroll", handler);
    };
  }, [key]);

  return null;
}

演示: https://codesandbox.io/s/relaxed-aryabhata-u1hgf

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM