【问题标题】:How to scroll to top on route change with react router dom v6?如何使用反应路由器 dom v6 在路由更改时滚动到顶部?
【发布时间】:2022-01-08 14:32:19
【问题描述】:

如何使用 react router 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),对我也不起作用。

【问题讨论】:

标签: javascript css reactjs react-router react-router-dom


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    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]);
    

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

    【讨论】:

      猜你喜欢
      • 2020-07-21
      • 2021-03-29
      • 2022-08-22
      • 1970-01-01
      • 2020-10-04
      • 2021-10-17
      • 2022-01-21
      • 2017-07-22
      • 2020-01-04
      相关资源
      最近更新 更多