gpt4 book ai didi

javascript - 如何使用 react 路由器 dom v6 在路由更改时滚动到顶部?

转载 作者:行者123 更新时间:2023-12-05 00:27:11 24 4
gpt4 key购买 nike

如何使用 react 路由器 dom v6 在路由更改时滚动到顶部?
我试过这个,react-router scroll to top on every transition ,这是我在使用 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) 的 Prop ,对我也不起作用。

最佳答案

好吧,我不太确定您的布局是什么样的,但在您的 <BrowserRouter /> 内您可以将您的应用程序包装在一个包装器中并检查 useLayoutEffect 中的位置更改.然后,如果有更改,您可以滚动到顶部。这是一个粗略的例子。
Codesandbox

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

关于javascript - 如何使用 react 路由器 dom v6 在路由更改时滚动到顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70193712/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com