我想在更改路线后滚动到页面顶部。但是,当用户按下浏览器中的“后退”按钮时,我希望他们返回到上一页的上一个滚动位置而不是顶部。我已经实现了 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>
答案 0 :(得分: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;
}