英文:
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 "react-router-dom";
import Header from "./Header";
import Header1 from "./Header1";
import Routes from "./Routes";
import Footer from "./Footer";
function App() {
const location = useLocation();
// Render Header1 on Complain page and Header on all other pages
const header = location.pathname === "/complain" ? <Header1 /> : <Header />;
return (
<>
{header}
<Routes />
<Footer />
</>
);
}
export default App;
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论