javascript React.js:停止渲染滚动到页面顶部

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30365818/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:05:37  来源:igfitidea点击:

React.js: Stop render from scrolling to top of page

javascriptjqueryreactjs

提问by Ben

Every time you perform a render in React.js, the UI scrolls to the top of the page.

每次在 React.js 中执行渲染时,UI 都会滚动到页面顶部。

JSFiddle: http://jsfiddle.net/bengrunfeld/dcfy5xrd/

JSFiddle:http: //jsfiddle.net/bengrunfeld/dcfy5xrd/

Any nifty or reactiveway to stop that?

任何漂亮或被动的方式来阻止它?

E.g. If a User scrolls down the page, then pushes a button which causes a Render, the UI would stay in the same scroll location as before.

例如,如果用户向下滚动页面,然后按下导致渲染的按钮,则 UI 将保持在与以前相同的滚动位置。

// Forces a render which scrolls to top of page
this.setState({data: data});

UPDATE: Why does the UI scroll to the top for some renders, but not others?

更新:为什么某些渲染的 UI 会滚动到顶部,而其他渲染则不会?

采纳答案by Ben

@floydophone answered this one on Twitter.

@floydophone 在 Twitter 上回答了这个问题。

https://twitter.com/floydophone/status/608129119025561600

https://twitter.com/floydophone/status/608129119025561600

@bengrunfeld @reactjs you forgot preventDefault()on your link handlers

@bengrunfeld @reactjs 你忘记preventDefault()了你的链接处理程序

回答by escalepion

Ok if anyone read this , in my case the problem wasn't any of above. You must try first suggestions on above any way. I did everything including preventDefault()but didn't help me. The problem was ; using styled-components. Because, styled-components give a random classname every render. So it resets scroll. I gave the class name from css and solved my problem.

好的,如果有人读过这篇文章,就我而言,问题不是以上任何一个。您必须以任何方式尝试上面的第一个建议。我做了一切,包括preventDefault()但没有帮助我。问题是; 使用styled-components. 因为,样式组件在每次渲染时都会给出一个随机的类名。所以它重置滚动。我从 css 中给出了类名并解决了我的问题。

回答by InnerException

Wanted to add here for those who are not using anchor tags, preventDefaultwill not save you. As bizarre as it is, for me it was related to rendering my child components inside a divwith

想在这里为那些不使用锚标签的人添加,preventDefault不会救你。尽管很奇怪,但对我来说这与将我的子组件渲染在一个divwith

display:table > display:tablecell

For some reason the child component's scroll position is lost in this situation when there is any re-render. Problem vanished when I switched to flexbox (display:flex).

出于某种原因,当有任何重新渲染时,子组件的滚动位置在这种情况下会丢失。当我切换到 flexbox (display:flex) 时,问题就消失了。

回答by Julian

If render trigger scrolling to the top it usually means some UI component is changing its dimension because of the state, this can be fixed by adding a minimum width/height

如果渲染触发器滚动到顶部通常意味着某些 UI 组件由于状态而改变其尺寸,这可以通过添加最小宽度/高度来解决