如何在两个不同页面上使用React中的两个导航栏

huangapple go评论56阅读模式
英文:

How to use two navbar in react on two different pages

问题

<>
  <Header />
  <Routes>
    <Route path='/' element={<Home />} />
    <Route path='application' element={<Application />} />
    <Route path='services' element={<Services />} />
    <Route path='subscription' element={<Subscription />} />
    <Route path='complain' element={<Header1 />} />
  </Routes>
  <Footer />
</>
英文:
<>  
  <Header />
  <Routes>      
    <Route path='/' element={<Home />} />
    <Route path='application' element={<Application />} />
    <Route path='services' element={<Services />} />
    <Route path='subscription' element={<Subscription />} />
    <Route path='complain' element={<Complain />} />
  </Routes>
  <Footer />
</>

I have created two headers (header, header1) I want to use header1 just on complain page and except complain page I want to use header but I don't know how to use it.

答案1

得分: 1

你可以使用条件渲染,并使用react-router-dom中的useLocation。因此,根据显示特定页眉的组件来决定显示哪个页眉。

import { useLocation } from "react-router-dom";
import Header from "./Header";
import Header1 from "./Header1";
import Routes from "./Routes";
import Footer from "./Footer";

function App() {
  const location = useLocation();

  // 在Complain页面上渲染Header1,在其他所有页面上渲染Header
  const header = location.pathname === "/complain" ? <Header1 /> : <Header />;

  return (
    <>
      {header}
      <Routes />
      <Footer />
    </>
  );
}

export default App;
英文:

You can use conditionally rendering. And use useLocation from react-router-dom. So base on the comp that are showing that certain header is showing aswell.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

import { useLocation } from &quot;react-router-dom&quot;;
import Header from &quot;./Header&quot;;
import Header1 from &quot;./Header1&quot;;
import Routes from &quot;./Routes&quot;;
import Footer from &quot;./Footer&quot;;

function App() {
  const location = useLocation();

  // Render Header1 on Complain page and Header on all other pages
  const header = location.pathname === &quot;/complain&quot; ? &lt;Header1 /&gt; : &lt;Header /&gt;;

  return (
    &lt;&gt;
      {header}
      &lt;Routes /&gt;
      &lt;Footer /&gt;
    &lt;/&gt;
  );
}

export default App;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月6日 17:52:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76188235.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定