reactjs - 如何修复 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 页”或网站底部的任何页面时,我希望该页面会在用户回到顶部的情况下加载。
实际行为:
用户停留在当前页面的滚动位置
解决方案
您还可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
推荐阅读
- arangodb - ArangoDB 在每个 int 的文档中排序
- java - 将 java8 迁移到 java11:import com.sun.security.auth.module.NTSystem
- python - 在 Apache 上找不到静态文件
- reactjs - 如何获取对象 ID onPress 并将该值传递到 React Native 中的新屏幕?
- javascript - 当列表中存在重复值时显示警报消息
- regex - 将文件夹中的所有页面重定向到单个 URL(主页)的 RewriteRule 是什么?
- command - SCons env.Command() 没有按预期工作,没有执行命令
- reactjs - TypeError: ShallowWrapper::dive() 不能在主机组件上调用
- swift - Swift Xib 子视图未填充视图
- html - 有没有办法用 CSS 或 PHP 内部改变 PHP 错误的样式?