如何使用REACT路由器DOM v6滚动到路由更改的顶部? [英] How to scroll to top on route change with react router dom v6?

查看:23
本文介绍了如何使用REACT路由器DOM v6滚动到路由更改的顶部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Reaction路由器DOM v6滚动到路由更改的顶部?

我已经尝试过react-router scroll to top on every transition,这是我的解决方案,当我使用react-router-domv5时,当我使用react-router-domv5时,这是我的页面在路由更改时滚动到顶部的解决方案。现在,我使用的是react-router-domv6,此解决方案不起作用。

我尝试了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滚动到路由更改的顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆