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

Next.js如何为部分路由对应页面的body元素添加自定义class

Pages Router 实现方案

在项目的pages/_app.js文件中添加路由监听逻辑,每次路由切换时动态更新body的类名:

import { useEffect } from 'react'
import { useRouter } from 'next/router'
import '../styles/globals.css'

export default function CustomApp({ Component, pageProps }) {
  const router = useRouter()
  // 定义不需要添加fixed-header类的路径列表
  const excludePaths = ['/cart/step-1', '/login']

  useEffect(() => {
    if (!excludePaths.includes(router.pathname)) {
      document.body.classList.add('fixed-header')
    } else {
      document.body.classList.remove('fixed-header')
    }
  // 依赖路由路径变化触发更新
  }, [router.pathname])

  return <Component {...pageProps} />
}

如果你需要匹配带参数的动态路径,可以把router.pathname换成router.asPath获取完整的实际访问路径。


App Router(Next.js 13+)实现方案

App Router支持直接在根布局组件中给body标签绑定动态类名,不需要操作DOM,实现更简洁:

  1. 给根app/layout.js添加'use client'客户端组件标记
  2. 用usePathname获取当前路由路径,动态拼接body的类名
'use client'
import { usePathname } from 'next/navigation'
import './globals.css'

export default function RootLayout({ children }) {
  const currentPath = usePathname()
  const excludePaths = ['/cart/step-1', '/login']
  // 拼接类名,默认保留bg-gray类
  const bodyClassName = `bg-gray ${!excludePaths.includes(currentPath) ? 'fixed-header' : ''}`

  return (
    <html lang="zh-CN">
      <body className={bodyClassName}>{children}</body>
    </html>
  )
}

注意事项

  • 如果项目配置了路径重定向、路由别名,建议统一用实际访问路径做匹配判断,避免匹配失效
  • 不推荐在Pages Router的_document.js中修改body类名,该文件仅在服务端渲染时执行,无法响应客户端路由切换的类名更新

内容的提问来源于stack exchange,提问作者S.M_Emamian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:06:01