【问题标题】:How to scroll to the top of the page after a route change, but retain the scroll position when going back?如何在路线更改后滚动到页面顶部,但返回时保留滚动位置?
【发布时间】:2021-07-08 13:06:36
【问题描述】:

我想在更改路线后滚动到页面顶部。但是,当用户在浏览器中按下“返回”按钮时,我希望他们返回到上一页的上一个滚动位置,而不是返回到顶部。我已经实现了 n“滚动到顶部”功能并且它有效 (Link)。但是,我想知道在“返回”时如何修改它以记住以前的滚动位置。

滚动到顶部:

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);

App.js

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

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    实现此目的的一种方法是通过位置键和窗口 x、y 坐标跟踪用户的位置。 react-router-dom 给出了一个好主意 here

    这是一个可能看起来像的示例。

    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

    【讨论】:

    • 谢谢丹尼斯。我会在晚上晚些时候检查代码。
    • 感谢它适用于 BrowserRouter 但不适用于 HashRouter。它将如何查找 BrowserRouter 的 HashRouter insetad?
    • @dan_boy HashRouter 不支持 location.key 这是这种方法背后的魔力。您可能希望查看window.onhashchange 以及自己生成和跟踪密钥。我建议专门为此提出一个新问题。
    猜你喜欢
    • 2014-01-30
    • 2015-10-25
    • 2020-08-08
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 2022-01-21
    • 2021-12-15
    相关资源
    最近更新 更多