简体   繁体   English

如何防止浏览器滚动到渲染顶部

[英]How do I prevent the browser from scrolling to the top on render

How do I prevent the browser from scrolling to the top on render? 如何防止浏览器滚动到渲染顶部? This can be reproduced at https://www.gatsbyjs.org/ or https://reactjs.org/ by going to the website with a throttled network connection and scrolling down before the page renders. 可以在https://www.gatsbyjs.org/https://reactjs.org/上进行复制,方法是通过节流的网络连接转到网站并在页面呈现之前向下滚动。

This doesn't happen when JS is disabled. 禁用JS时不会发生这种情况。 I believe this a Gatsby only problem. 我相信这是盖茨比唯一的问题。

This ended up being a bug in Gatsby, which can be tracked at https://github.com/gatsbyjs/gatsby/issues/6392#issuecomment-404444341 . 这最终是Gatsby中的错误,可以在https://github.com/gatsbyjs/gatsby/issues/6392#issuecomment-404444341处进行跟踪。

One way around this is to disable scrolling before the component has been mounted and then reenabling it. 解决此问题的一种方法是在安装组件之前禁用滚动,然后重新启用它。 This can be done with the following style change: 可以通过以下样式更改来完成:

// styles.css
body {
  overflow: hidden;
}

// Component.js
componentDidMount () {
  document.body.style.overflow = 'auto'
}

As Ben said: try adding preventDefault() on your link handlers. 正如Ben所说:尝试在链接处理程序上添加preventDefault()

React.js: Stop render from scrolling to top of page React.js:停止渲染从滚动到页面顶部

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM