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

NextJs 13.4中404页面的两个技术问题咨询

Next.js 两个问题的解决方案

问题一:移除404页面的导航栏

方案:拆分嵌套布局(最稳妥)

把根布局作为无导航栏的基础布局,再创建一个带导航栏的子布局,让需要显示导航栏的页面归属于这个子布局目录下,404页面保留在根目录,自然不会继承带导航栏的布局。

  1. 根app/layout.tsx(基础布局,无导航栏):
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'

const inter = Inter({ subsets: ['latin'] })

export const metadata: Metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body className={inter.className}>{children}</body>
    </html>
  )
}
  1. 创建app/(with-navbar)/layout.tsx(带导航栏的子布局):
import Navbar from '../components/Navbar'

export default function WithNavbarLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <>
      <Navbar />
      <main>{children}</main>
    </>
  )
}
  1. 调整页面结构:将所有需要显示导航栏的页面移至app/(with-navbar)/目录下,not-found.tsx保留在app/根目录。

访问404页面时,只会加载根布局,不会显示导航栏。


问题二:为所有页面(含404)的body添加自定义类

无需将整个根布局改为客户端组件,只需创建一个轻量的客户端组件处理body类的添加与移除:

  1. 创建app/components/BodyClass.tsx:
'use client'

import { useEffect } from 'react'

export default function BodyClass({ className }: { className: string }) {
  useEffect(() => {
    document.body.classList.add(className)
    // 组件卸载时移除类,避免污染其他页面
    return () => document.body.classList.remove(className)
  }, [className])

  return null
}
  1. 在根app/layout.tsx中引入该组件:
import type { Metadata } from 'next'
import { Inter } from 'next/font/google'
import BodyClass from './components/BodyClass'

const inter = Inter({ subsets: ['latin'] })

export const metadata: Metadata = {
  title: 'Create Next App',
  description: 'Generated by create next app',
}

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <BodyClass className="your-custom-body-class" />
      <body className={inter.className}>{children}</body>
    </html>
  )
}

这种方式既保留了根布局的服务器组件特性(性能更优),又能让所有页面(包括404)的body都添加上自定义类。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:57:27