You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React.js中仅让Banner和Department组件显示在首页

解决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;

关键改动说明:

  1. 新增导入useLocation:import { Redirect, useLocation } from "react-router-dom";
  2. 获取当前路由信息:const location = useLocation();
  3. 判断是否为首页:const isHomePage = location.pathname === "/";,如果你的首页路由是/home这类非根路径,直接替换引号内的内容即可
  4. 条件渲染组件:通过{isHomePage && <组件 />}的语法,只有当处于首页时才会渲染对应的组件

这样切换到其他路由页面时,Banner和Department会自动隐藏,仅在首页展示。

内容的提问来源于stack exchange,提问作者Shivam Pandey

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 20:46:01