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

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

How to use two navbar in react on two different pages

问题

  1. <>
  2. <Header />
  3. <Routes>
  4. <Route path='/' element={<Home />} />
  5. <Route path='application' element={<Application />} />
  6. <Route path='services' element={<Services />} />
  7. <Route path='subscription' element={<Subscription />} />
  8. <Route path='complain' element={<Header1 />} />
  9. </Routes>
  10. <Footer />
  11. </>
英文:
  1. <>
  2. <Header />
  3. <Routes>
  4. <Route path='/' element={<Home />} />
  5. <Route path='application' element={<Application />} />
  6. <Route path='services' element={<Services />} />
  7. <Route path='subscription' element={<Subscription />} />
  8. <Route path='complain' element={<Complain />} />
  9. </Routes>
  10. <Footer />
  11. </>

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。因此,根据显示特定页眉的组件来决定显示哪个页眉。

  1. import { useLocation } from "react-router-dom";
  2. import Header from "./Header";
  3. import Header1 from "./Header1";
  4. import Routes from "./Routes";
  5. import Footer from "./Footer";
  6. function App() {
  7. const location = useLocation();
  8. // 在Complain页面上渲染Header1,在其他所有页面上渲染Header
  9. const header = location.pathname === "/complain" ? <Header1 /> : <Header />;
  10. return (
  11. <>
  12. {header}
  13. <Routes />
  14. <Footer />
  15. </>
  16. );
  17. }
  18. 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 -->

  1. import { useLocation } from &quot;react-router-dom&quot;;
  2. import Header from &quot;./Header&quot;;
  3. import Header1 from &quot;./Header1&quot;;
  4. import Routes from &quot;./Routes&quot;;
  5. import Footer from &quot;./Footer&quot;;
  6. function App() {
  7. const location = useLocation();
  8. // Render Header1 on Complain page and Header on all other pages
  9. const header = location.pathname === &quot;/complain&quot; ? &lt;Header1 /&gt; : &lt;Header /&gt;;
  10. return (
  11. &lt;&gt;
  12. {header}
  13. &lt;Routes /&gt;
  14. &lt;Footer /&gt;
  15. &lt;/&gt;
  16. );
  17. }
  18. 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:

确定