[英]Link going to last scroll position instead of anchor
On my React app, I have two pages: page A, the home page, and page B.在我的 React 应用程序中,我有两个页面:页面 A、主页和页面 B。
On page B, I have links that go to page A in a specific section.在页面 B 上,我有指向特定部分中页面 A 的链接。
On page A: <section id="foo">Foo</section>
在 A 页:
<section id="foo">Foo</section>
On page B: <a href="/#foo">Go to foo</a>
在 B 页:
<a href="/#foo">Go to foo</a>
Every time I go to page B from page A and click on the link, the screen goes to the last scroll position and not the section.每次我从 A 页转到 B 页并单击链接时,屏幕都会转到最后一个滚动位置而不是该部分。
I tried to deactivate the browser scroll history function with:我尝试使用以下方法停用浏览器滚动历史记录功能:
useEffect(() => {
if (history.scrollRestoration) {
history.scrollRestoration = 'manual';
}
}, []);
I also to tried to add function to go to desired section:我还尝试添加功能以转到所需部分:
useEffect(() => {
if (window.location.hash) {
const anchor = document.querySelector(window.location.hash);
anchor.scrollIntoView();
}
}, []);
But none of these solutions works.但是这些解决方案都不起作用。 I reproduce the same behaviour on Chrome and Firefox.
我在 Chrome 和 Firefox 上重现了相同的行为。
It was a Gatsby feature: it overrides the browser default scroll history behaviour.这是 Gatsby 的一个特性:它覆盖了浏览器默认的滚动历史行为。 More info there https://www.gatsbyjs.com/docs/how-to/routing/scroll-restoration/
更多信息https://www.gatsbyjs.com/docs/how-to/routing/scroll-restoration/
I fixed it by adding:我通过添加来修复它:
// gatsby-browser.js
exports.shouldUpdateScroll = ({
routerProps: { location },
getSavedScrollPosition,
}) => {
return location.href.indexOf("#") > -1 ? false : true;
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.