首页 > 解决方案 > 如何修复 Gatsby JS Link 组件保留滚动位置而不重置到顶部

问题描述

我正在使用 Gatsby 2.2.10 建立一个网站,并且链接组件保留上一页的滚动位置,并且在单击它们时不会滚动回顶部。

<div className="Footer__legal body">
 <p>© {new Date().getFullYear()} My Nice Company</p>
 <Link to="/privacy-policy">Privacy Policy</Link>
 <Link to="/page-2">Page 2 Link component</Link>
</div>

预期行为:

当您单击“隐私政策”、“第 2 页”或网站底部的任何页面时,我希望该页面会在用户回到顶部的情况下加载。

实际行为:

用户停留在当前页面的滚动位置

标签: reactjsgatsby

解决方案


您还可gatsby-browser.js以为每个滚动更新修改和实现一个钩子:

// in gastby-browser.js
exports.shouldUpdateScroll = ({
  routerProps: { location },
  getSavedScrollPosition,
}) => {
  const { pathname } = location
  // list of routes for the scroll-to-top-hook
  const scrollToTopRoutes = [`/privacy-policy`, `/page-2`]
  // if the new route is part of the list above, scroll to top (0, 0)
  if (scrollToTopRoutes.indexOf(pathname) !== -1) {
    window.scrollTo(0, 0)
  }

  return false
}

您可以shouldUpdateScroll在 GitHub或GatsbyJS 网站上的文档中找到代码。shouldUpdateScroll


推荐阅读