react-router在每次转换时滚动到顶部 [英] react-router scroll to top on every transition
问题描述
导航到另一个页面时出现问题,其位置将保持与之前的页面相同。所以它不会自动滚动到顶部。
我也尝试在onChange路由器上使用 window.scrollTo(0,0)
。我也使用scrollBehavior来解决这个问题,但它没有用。有什么建议吗?
I have an issue when navigating into another page, its position will remain like the page before. So it wont scroll to top automatically.
I've also tried to use window.scrollTo(0, 0)
on onChange router. I've also used scrollBehavior to fix this issue but it didnt work. Any suggestion about this?
推荐答案
React Router v4的文档包含代码示例。这是他们的第一个代码示例,当页面导航到以下时,它作为滚动到顶部的站点范围解决方案:
The documentation for React Router v4 contains code samples for scroll restoration. Here is their first code sample, which serves as a site-wide solution for "scroll to the top" when a page is navigated to:
class ScrollToTop extends Component {
componentDidUpdate(prevProps) {
if (this.props.location !== prevProps.location) {
window.scrollTo(0, 0)
}
}
render() {
return this.props.children
}
}
export default withRouter(ScrollToTop)
然后将其呈现在应用程序的顶部,但在路由器下方:
Then render it at the top of your app, but below Router:
const App = () => (
<Router>
<ScrollToTop>
<App/>
</ScrollToTop>
</Router>
)
// or just render it bare anywhere you want, but just one :)
<ScrollToTop/>
显然这适用于大多数情况,但有更多的是如何处理选项卡式接口以及为什么没有实现通用解决方案。
Obviously this works for most cases, but there is more on how to deal with tabbed interfaces and why a generic solution hasn't been implemented.
这篇关于react-router在每次转换时滚动到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!