How to scroll to top on route change with react router dom v6?(如何使用REACT路由器DOM v6滚动到路由更改的顶部?)
问题描述
如何使用Reaction路由器DOM v6滚动到路由更改的顶部?
我已经尝试过react-router scroll to top on every transition,这是我的解决方案,当我使用react-router-dom
v5时,当我使用react-router-dom
v5时,这是我的页面在路由更改时滚动到顶部的解决方案。现在,我使用的是react-router-dom
v6,此解决方案不起作用。
我尝试了React-router v6 window.scrollTo does not work,但对我无效。
我尝试了https://github.com/remix-run/react-router/issues/7365,即使用preload
道具触发scrollTo(0,0)
,但对我也不起作用。
推荐答案
我不太确定您的布局是什么样子,但是在您的<BrowserRouter />
中,您可以将您的应用程序包装在一个包装器中,并在useLayoutEffect
中检查位置更改。如果有变化,您可以滚动到顶部。这里有一个粗略的例子。
import { BrowserRouter, Routes, Route, Link, useLocation } from 'react-router-dom'
import { useLayoutEffect } from 'react'
const Wrapper = ({children}) => {
const location = useLocation();
useLayoutEffect(() => {
document.documentElement.scrollTo(0, 0);
}, [location.pathname]);
return children
}
const Component = ({title}) => {
return (
<div>
<p style={{paddingTop: '150vh'}}>{title}</p>
</div>
)
}
const App = () => {
return (
<BrowserRouter>
<Wrapper>
<p>Scroll the bottom to change pages</p>
<Routes>
<Route path="/" element={<Component title="Home"/>} />
<Route path="/about" element={<Component title="About"/>} />
<Route path="/product" element={<Component title="Product"/>} />
</Routes>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/product">Product</Link>
</Wrapper>
</BrowserRouter>
)
}
export default App
这篇关于如何使用REACT路由器DOM v6滚动到路由更改的顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用REACT路由器DOM v6滚动到路由更改的顶部?


基础教程推荐
- 动态更新多个选择框 2022-01-01
- 在for循环中使用setTimeout 2022-01-01
- 悬停时滑动输入并停留几秒钟 2022-01-01
- 角度Apollo设置WatchQuery结果为可用变量 2022-01-01
- 在 JS 中获取客户端时区(不是 GMT 偏移量) 2022-01-01
- 响应更改 div 大小保持纵横比 2022-01-01
- 有没有办法使用OpenLayers更改OpenStreetMap中某些要素 2022-09-06
- Karma-Jasmine:如何正确监视 Modal? 2022-01-01
- 我什么时候应该在导入时使用方括号 2022-01-01
- 当用户滚动离开时如何暂停 youtube 嵌入 2022-01-01