我如何根据路线在 app.js 中有条件地 return 不同的 navbars/headers?

How can I conditionally return different navbars/headers in app.js based on the route?

我找不到任何明确的答案,所以我想问一下。我正在尝试为两条不同的路线呈现 2 个不同的 header。所以理想情况下,如果我们在 '/home' 上,我们 return 装扮得很好 <HeaderHome />,如果我们在 '/projects' 路线上,那么渲染一个更简单的 [=22] =] 在 <HeaderProjects /> 中。下面是我的代码结构。

function App() {
  return (
    <>
      <div className={styles.container}>
        <main className={styles.main}>
          {(path == "/home") ? <HeaderHome /> : <HeaderProjects />}   
          <Routes>
              <Route path="/home" element={< Home />} />
              {/* <Route path="/about" element={< About />} />
              <Route path="/resume" element={<Resume />} /> */}
              <Route path="/projects" element={<Projects />} />           
              {/* <Route path="/contact" element={<Contact />} />     */}
          </Routes>
          <Footer /> 
        </main>
      </div>
    </>
  )
}

感谢您的观看。

您可以使用呈现所需特定 header 组件的布局组件和用于嵌套路由的 Outlet

示例:

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

const HomeLayout = () => (
  <>
    <HeaderHome />
    <Outlet />
  </>
);

const ProjectsLayout = () => (
  <>
    <HeaderProjects />
    <Outlet />
  </>
);

function App() {
  return (
    <div className={styles.container}>
      <main className={styles.main}>
        <Routes>
          <Route element={<HomeLayout />}>
            <Route path="/home" element={<Home />} />
          </Route>

          <Route element={<ProjectsLayout />}>
            <Route path="/projects" element={<Projects />} /> 
          </Route>

          <Route path="/about" element={<About />} />
          <Route path="/resume" element={<Resume />} />          
          <Route path="/contact" element={<Contact />} />
        </Routes>
        <Footer /> 
      </main>
    </div>
  );
}