Has*_*zad 3 scroll wrapper react-router-dom
我在 Reactjs 上创建了一个网站,并使用“react-router-dom v6”链接了各个页面。每当我从一个页面转换到另一个页面时,第二页总是加载到当前位置而不是顶部。我已经尝试了很多教程和解决方案,但它们在react-router-dom v5之前都有效。
我通过创建一个包装函数并将其包装在所有路由周围解决了以下问题。
请按照以下步骤操作:
1:您需要导入以下内容:
import {Routes, Route, BrowserRouter as Router, useLocation} from 'react-router-dom';
import {useLayoutEffect} from 'react';
Run Code Online (Sandbox Code Playgroud)
2:在“App”函数上方编写一个包装函数:
const Wrapper = ({children}) => {
const location = useLocation();
useLayoutEffect(() => {
document.documentElement.scrollTo(0, 0);
}, [location.pathname]);
return children
}
Run Code Online (Sandbox Code Playgroud)
3:现在将您的路由包装在包装函数中:
<BrowserRouter>
<Wrapper>
<Navbar />
<Routes>
<Route exact path="/" element={<Home/>} />
<Route path="/Products" element={<Products/>} />
<Route path="/Login" element={<Login/>} />
<Route path="/Aggressive" element={<Aggressive/>} />
<Route path="/Attendance" element={<Attendance/>} />
<Route path="/Choking" element={<Choking/>} />
<Route path="/EmptyCounter" element={<EmptyCounter/>} />
<Route path="/FaceMask" element={<FaceMask/>} />
<Route path="/Fainting" element={<Fainting/>} />
<Route path="/Smoking" element={<Smoking/>} />
<Route path="/SocialDistancing" element={<SocialDistancing/>} />
<Route path="/Weapon" element={<Weapon/>} />
</Routes>
<Footer />
</Wrapper>
</BrowserRouter>
Run Code Online (Sandbox Code Playgroud)
这应该可以解决问题。
归档时间: |
|
查看次数: |
4060 次 |
最近记录: |