[英]How to scroll to the top of the page after a route change, but retain the scroll position when going back?
I want to scroll to the top of the page after changing the route.我想在更改路线后滚动到页面顶部。 However, when the user presses the "Back" button in the browser, I want them to return to the previous scroll position on the previous page and NOT to the top.但是,当用户在浏览器中按下“返回”按钮时,我希望他们返回上一页上的上一个滚动 position 而不是顶部。 I have implemented n "scroll to the top" feature and it works ( Link ).我已经实现了 n“滚动到顶部”功能并且它有效( 链接)。 However, I am wondering how I need to modify it to remember the previous scroll position, when going "Back".但是,我想知道在“返回”时如何修改它以记住以前的滚动 position。
Scroll to Top:滚动到顶部:
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应用程序.js
<ScrollToTop>
<Switch>
<PublicRoute exact path="/join/" component={LandingPage} />
</Switch>
</ScrollToTop>
One way you can accomplish this is by tracking where the user is via the location key and the window x, y coords.实现此目的的一种方法是通过位置键和 window x、y 坐标跟踪用户的位置。 react-router-dom
gives a good idea here . react-router-dom
在这里给出了一个好主意。
Here's an example of what that might look like.这是一个可能看起来像的示例。
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;
}
Demo: https://codesandbox.io/s/relaxed-aryabhata-u1hgf演示: https://codesandbox.io/s/relaxed-aryabhata-u1hgf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.