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

React项目如何根据当前路由/组件动态修改Header显示的页面标题

React Router 动态设置Header页面标题实现方案

方案1:抽离路由配置(易维护,推荐)

这种方式把路由信息统一维护,后续新增/修改路由不需要改动Header组件逻辑。

  1. 首先抽离公共路由配置,新建routeConfig.js文件:
import AvailableData from './components/AvailableData'
// 引入其他页面组件...

export const routeConfig = [
  {
    path: '/',
    component: AvailableData,
    title: 'Available data',
    exact: true
  },
  {
    path: '/available-data',
    component: AvailableData,
    title: 'Available data'
  },
  // 其余路由按相同格式添加
  // {
  //   path: '/your-path',
  //   component: YourComponent,
  //   title: '对应页面标题'
  // }
]
  1. 调整App.js的路由渲染逻辑,直接遍历配置生成路由:
import { BrowserRouter as Router, Route } from 'react-router-dom'
import { routeConfig } from './routeConfig'
import Header from './components/Header'
import Navbar from './components/Navbar'

function App() {
  return (
    <Router>
      {/* Header需要放在Router内部才能拿到路由信息 */}
      <Header />
      <Navbar />
      {routeConfig.map(route => (
        <Route
          key={route.path}
          exact={route.exact}
          path={route.path}
          component={route.component}
        />
      ))}
    </Router>
  )
}
  1. 改造Header组件,根据当前路由匹配对应标题:
import { useLocation } from 'react-router-dom'
import { routeConfig } from '../routeConfig'

function Header() {
  const location = useLocation()
  // 匹配当前路径对应的路由配置
  const currentRoute = routeConfig.find(route => {
    return route.exact 
      ? location.pathname === route.path 
      : location.pathname.startsWith(route.path)
  })
  // 匹配不到时显示默认标题
  const title = currentRoute?.title ?? '默认页面标题'

  return (
    <div className="app-header">
      <div className="app-header__title">
        {title}
      </div>
    </div>
  )
}

方案2:直接维护路径-标题映射(适合小型项目)

如果项目路由数量少,不想抽离配置,可以直接在Header组件内维护映射关系:

import { useLocation } from 'react-router-dom'

function Header() {
  const location = useLocation()
  const titleMap = {
    '/': 'Available data',
    '/available-data': 'Available data',
    // 其余路径和标题的映射
    // '/other-path': '其他页面标题'
  }
  const title = titleMap[location.pathname] ?? '默认页面标题'

  return (
    <div className="app-header">
      <div className="app-header__title">
        {title}
      </div>
    </div>
  )
}

注意:如果运行时出现useLocation() may be used only in the context of a Router component报错,说明Header组件没有放在Router组件的子节点范围内,调整组件嵌套层级即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 05:09:02