我已将 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”直接导航到页面的联系部分时,它不会导航。你能帮我理解哪里出了问题吗?
我能够通过使用 React 生命周期和
scrollIntoView
解决我的问题
componentDidMount() {
const urlHash = window.location.hash;
if (urlHash.length) {
const element = document.getElementById(urlHash.substring(1));
if (element) {
element.scrollIntoView();
}
}
}
对于功能组件
useState
钩子与@grishma的答案配合得很好。
useEffect(() => {
const urlHash = window.location.hash;
if (urlHash.length) {
const element = document.getElementById(urlHash.substring(1));
if (element) {
element.scrollIntoView();
}
}
});