简体   繁体   English

React 初学者和使用 React Router Dom v6 在页面之间导航

[英]Beginner to React and Using React Router Dom v6 to navigate between pages

I'm struggling to navigate between different pages in react router I have my ReactDom.render() as follows:我正在努力在反应路由器的不同页面之间导航我有我的 ReactDom.render() 如下:

ReactDOM.render((
  <BrowserRouter>
    <App/>
  </BrowserRouter>),
  document.getElementById('root'))
  

Here I have App.js with just my home and a second page (Park).在这里,我有 App.js,只有我的主页和第二页 (Park)。 If I place outside the tags the navbar is visible, but when inside the tags the navbar isn't visible anymore.如果我放在标签外面,导航栏是可见的,但是当我放在标签里面时,导航栏就不再可见了。

function App() {
  
  const classes = styles();
  return (
    <>
      <Router>
        <NavBar />

        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/park_your_car" element={<Park />} />

        </Routes>
      </Router>
    </>
  );
}

export default App;

Then I placed my links inside my NavBar.js然后我将我的链接放在我的 NavBar.js 中

function NavBar() {
    const classes = styles()
    return (
        <div>
        
        <Toolbar position = "sticky" color="rgba(255, 215, 0)" className={classes.bar}>
        <img src={logo} className={classes.logo}/>
        
        <Typography variant="h6" className={classes.menuItem}>
            
                <Link to="/"><b>Home</b> </Link>
            
        </Typography>
        <Typography variant="h6" className={classes.menuItem}>
            
                <Link to="/park_your_car"><b>Park Your Car</b></Link>
            
        </Typography>
        <Typography variant="h6" className={classes.menuItem}>
            
                <Link className="menuItem" to="/find_your_car"><b>Find Your Car</b></Link>
            
        </Typography>
        <Typography variant="h6" className={classes.menuItem}>
            
                <Link className="menuItem" to="/exit_from_lot"><b>Exit Lot</b></Link>
            
        </Typography>
        <CustomButton txt="Contact Us" />        
        </Toolbar>
        </div>
    )
}

You should remove <Router> tag and take out <Navbar> from the <Routes>您应该删除<Router>标签并从<Routes>中取出<Navbar> >

function App() {
  
  const classes = styles();
  return (
    <>
        <NavBar />

        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/park_your_car" element={<Park />} />
        </Routes>
    </>
  );
}

Why you should remove <Router> from App?为什么要从 App 中删除<Router>

Because here, in index.js, you are already using BrowserRouter因为在这里,在 index.js 中,你已经在使用BrowserRouter

import { BrowserRouter } from 'react-router-dom';

ReactDOM.render((
  <BrowserRouter>
    <App/>
  </BrowserRouter>),
  document.getElementById('root'))

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

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