如何导航到 React Router 中的部分

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

我正在尝试使用 React Router 导航到页面上的特定部分,但结果却落在页面顶部。手动输入网址确实会将我带到正确的位置。我做错了什么?

function App() {
  return (
    <>
      <Router>
        <Link to="/navbar#section2">Go to section 2</Link>
        <Link to="/navbar#section1">Go to section 1</Link>
        <Sidebar />
        <Switch>
          <Route path="/navbar" exact component={Navbar} />
        </Switch>
      </Router>
    </>
  );
}

reactjs react-router
2个回答
0
投票

您可以使用普通的

<a>
标签而不是
Link
组件来实现所需的功能

试试这个:

function App() {
  return (
    <>
      <Router>
        <a href="#section2">Go to section 2</a>
        <a href="#section1">Go to section 1</a>
        <Sidebar />
        <Switch>
          <Route path="/navbar" exact component={Navbar} />
        </Switch>
      </Router>
    </>
  );
}

0
投票

你找到答案了吗,3年后还有同样的问题??????

© www.soinside.com 2019 - 2024. All rights reserved.