NextJs 13.4中404页面的两个技术问题咨询
Next.js 两个问题的解决方案
问题一:移除404页面的导航栏
方案:拆分嵌套布局(最稳妥)
把根布局作为无导航栏的基础布局,再创建一个带导航栏的子布局,让需要显示导航栏的页面归属于这个子布局目录下,404页面保留在根目录,自然不会继承带导航栏的布局。
- 根
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> ) }
- 创建
app/(with-navbar)/layout.tsx(带导航栏的子布局):
import Navbar from '../components/Navbar' export default function WithNavbarLayout({ children, }: { children: React.ReactNode }) { return ( <> <Navbar /> <main>{children}</main> </> ) }
- 调整页面结构:将所有需要显示导航栏的页面移至
app/(with-navbar)/目录下,not-found.tsx保留在app/根目录。
访问404页面时,只会加载根布局,不会显示导航栏。
问题二:为所有页面(含404)的body添加自定义类
无需将整个根布局改为客户端组件,只需创建一个轻量的客户端组件处理body类的添加与移除:
- 创建
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 }
- 在根
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
相关产品推荐
相关产品推荐

