繁体   English   中英

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

[英]How to scroll to top on route change with react router dom v6?

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

我试过这个, react-router 在每次转换时滚动到顶部,这是我使用react-router-dom v5 时让我的页面在路由更改时滚动到顶部的解决方案。 现在,我正在使用react-router-dom v6,这个解决方案不起作用。

我试过React-router v6 window.scrollTo 不起作用,对我不起作用。

我尝试了 https://github.com/remix-run/react-router/issues/7365 ,这是使用preload道具来触发scrollTo(0,0) ,对我也不起作用。

这篇文章解决了这个问题看到它 -> https://www.matthewhoelter.com/2022/04/02/how-to-scroll-to-top-on-route-change-with-react-router-dom-v6 .html

制作ScrollToTop组件

然后添加此代码初始化

import { useLocation } from "react-router-dom";

export default function ScrollToTop() {
  const { pathname } = useLocation();

  useEffect(() => {
    // "document.documentElement.scrollTo" is the magic for React Router Dom v6
    document.documentElement.scrollTo({
      top: 0,
      left: 0,
      behavior: "instant", // Optional if you want to skip the scrolling animation
    });
  }, [pathname]);

  return null;
}

然后将其导入您的 App.js,现在您的问题已解决

见 img

const scrollToPosition = (top = 0) => {
  try {
    /**
     * Latest API
     */
    window.scroll({
      top: top,
      left: 0,
      behavior: "smooth",
    });
  } catch (_) {
    /**
     * Fallback
     */
    window.scrollTo(0, top);
  }
};

您可以使用上面的代码滚动顶部。

const didMount = useDidMount();
const router = useRouter();
const { asPath } = router;
useEffect(() => {
    if (didMount) {
      scrollToPosition();
    }
  }, [asPath]);

并将上面的代码添加到顶层父组件中。

好吧,我不确定您的布局是什么样的,但是在您的<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

window function 在较新版本的react中无法访问,最好使用useRef Hook。

const myRef = useRef<any>(null);
const executeScroll = () => myRef.current.scrollIntoView({inline: "center"});

useEffect(() => {
    executeScroll();
  }, [location.pathname]);
  
// YOUR COMPONENTS CODE
// I have my toolbar as the ref
<Toolbar ref={myRef}/>

这将在使用 useNavigator 和路径名更改时滚动。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM