如何在React.js中仅让Banner和Department组件显示在首页
要实现仅在首页展示Banner和Department组件、其他路由页面隐藏它们的需求,只需借助react-router-dom的useLocation钩子判断当前路由路径即可,具体操作如下:
- 从
react-router-dom中导入useLocation钩子 - 获取当前页面的路由路径,判断是否为首页(默认路径为
/,若你的首页路径不同可自行替换) - 仅当处于首页时,才渲染Banner和Department组件
修改后的完整代码:
import React from "react"; import "./App.css"; import "bootstrap/dist/css/bootstrap.css"; import Department from "./components/Dept"; import Banner from "./components/Banner"; import Footer from "./components/footer"; import LinksPosition from "./components/NavBar"; import { Redirect, useLocation } from "react-router-dom"; function App() { const shouldRedirect = false; // 自定义你的重定向条件 const location = useLocation(); const isHomePage = location.pathname === "/"; if (shouldRedirect) { return <Redirect to="/LinksPosition" />; } const bannerContent = "This is the banner content for all pages"; const departmentContent = "This is the department content for all pages"; return ( <> <LinksPosition /> {/* 仅在首页渲染Banner组件 */} {isHomePage && <Banner content={bannerContent} />} {/* 仅在首页渲染Department组件 */} {isHomePage && <Department content={departmentContent} />} <Footer /> </> ); } export default App;
关键改动说明:
- 新增导入
useLocation:import { Redirect, useLocation } from "react-router-dom"; - 获取当前路由信息:
const location = useLocation(); - 判断是否为首页:
const isHomePage = location.pathname === "/";,如果你的首页路由是/home这类非根路径,直接替换引号内的内容即可 - 条件渲染组件:通过
{isHomePage && <组件 />}的语法,只有当处于首页时才会渲染对应的组件
这样切换到其他路由页面时,Banner和Department会自动隐藏,仅在首页展示。
内容的提问来源于stack exchange,提问作者Shivam Pandey
相关产品推荐
相关产品推荐

