如何使用 React Router 在页面加载时导航到页面的特定部分?

问题描述 投票:0回答:2

我已将 BrowserRouter 添加到我的 React 应用程序中

   <BrowserRouter>
     <Routes>
        <Route path="/" element={<App/>}/>
     </Routes>
   </BrowserRouter>

这就是我的应用程序的样子:

<div className="App">
  <NavBar/>
  <Home/>
  <Contact/>
</div>

我的组件看起来像这样:

 <div id="contact" className="Contact"/>

当我尝试使用链接“mySite.com/#contact”直接导航到页面的联系部分时,它不会导航。你能帮我理解哪里出了问题吗?

html reactjs react-router-dom
2个回答
4
投票

我能够通过使用 React 生命周期和

scrollIntoView

解决我的问题
  componentDidMount() {
    const urlHash = window.location.hash;
    if (urlHash.length) {
      const element = document.getElementById(urlHash.substring(1));
      if (element) {
        element.scrollIntoView();
      }
    }
  }

0
投票

对于功能组件

useState
钩子与@grishma的答案配合得很好。

useEffect(() => {
    const urlHash = window.location.hash;
    if (urlHash.length) {
        const element = document.getElementById(urlHash.substring(1));
        if (element) {
            element.scrollIntoView();
        }
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.