layout.js
layout.js 文件的 API 参考。
layout 文件用于在 Next.js 应用中定义布局。
TypeScript
export default function DashboardLayout({
children,
}: {
children: React.ReactNode
}) {
return <section>{children}</section>
}
JavaScript
export default function DashboardLayout({ children }) {
return <section>{children}</section>
}
在组件层次结构中,layout.js 是路由段中最外层的组件。它包裹 template.js、error.js、loading.js、not-found.js 和 page.js。
根布局是根 app 目录中最顶层的布局。它用于定义 <html> 和 <body> 标签以及其他全局共享的 UI。
TypeScript
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
JavaScript
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
参考
Props
children(必填)
布局组件应接受并使用 children prop。在渲染期间,children 会被填充为该布局所包裹的路由段。这些主要是子级 Layout(如果存在)或 Page 的组件,但在适用情况下也可以是其他特殊文件,例如 Loading 或 Error。
params(可选)
一个 promise,它解析为一个对象,该对象包含从根段一直到该布局的动态路由参数对象。
TypeScript
export default async function Layout({
children,
params,
}: {
children: React.ReactNode
params: Promise<{ team: string }>
}) {
const { team } = await params
}
JavaScript
export default async function Layout({ children, params }) {
const { team } = await params
}
| 示例路由 | URL | params |
|---|---|---|
app/dashboard/[team]/layout.js |
/dashboard/1 |
Promise<{ team: '1' }> |
app/shop/[tag]/[item]/layout.js |
/shop/1/2 |
Promise<{ tag: '1', item: '2' }> |
app/blog/[...slug]/layout.js |
/blog/1/2 |
Promise<{ slug: ['1', '2'] }> |
- 由于
paramsprop 是一个 promise,你必须使用async/await或 React 的use函数来访问这些值。- 在版本 14 及更早版本中,
params是一个同步 prop。为了帮助实现向后兼容,在 Next.js 15 中你仍然可以同步访问它,但此行为将来会被弃用。
- 在版本 14 及更早版本中,
布局 Props 辅助工具
你可以使用 LayoutProps 为布局添加类型,从而获得强类型的 params 以及从目录结构推断出的具名插槽。LayoutProps 是一个全局可用的辅助工具。
export default function Layout(props: LayoutProps<'/dashboard'>) {
return (
<section>
{props.children}
{/* If you have app/dashboard/@analytics, it appears as a typed slot: */}
{/* {props.analytics} */}
</section>
)
}
须知:
- 类型在
next dev、next build或next typegen期间生成。- 类型生成后,
LayoutProps辅助函数即可全局使用,无需导入。
根布局
app 目录必须包含一个根布局,它是根 app 目录中最顶层的布局。通常,根布局是 app/layout.js。
TypeScript
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
JavaScript
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
- 根布局必须定义
<html>和<body>标签。- 你不应手动向根布局添加
<head>标签,例如<title>和<meta>。相反,你应该使用 Metadata API,它会自动处理流式渲染和去重<head>元素等高级需求。
- 你不应手动向根布局添加
- 你可以创建多个根布局。任何上方没有
layout.js的布局都是根布局。两种常见方法:- 使用 路由组,例如
app/(shop)/layout.js和app/(marketing)/layout.js - 省略
app/layout.js,使app/dashboard/layout.js和app/blog/layout.js等子目录中的布局各自成为其所在目录的根布局。 - 在多个根布局之间导航会导致整页加载(而不是客户端导航)。
- 使用 路由组,例如
- 根布局可以位于动态段之下,例如使用
app/[lang]/layout.js实现国际化时。根布局之前的动态段是根参数,可以在任何服务器组件中使用next/root-params读取。
注意事项
请求对象
导航期间,布局会在客户端中缓存,以避免不必要的服务器请求。
布局不会重新渲染。它们可以被缓存并复用,以避免在页面之间导航时进行不必要的计算。通过限制布局访问原始请求,Next.js 可以防止在布局中执行可能缓慢或昂贵的用户代码,从而避免对性能产生负面影响。
要访问请求对象,你可以在服务器组件和函数中使用 headers 和 cookies API。
TypeScript
import { cookies } from 'next/headers'
export default async function Layout({ children }) {
const cookieStore = await cookies()
const theme = cookieStore.get('theme')
return '...'
}
JavaScript
import { cookies } from 'next/headers'
export default async function Layout({ children }) {
const cookieStore = await cookies()
const theme = cookieStore.get('theme')
return '...'
}
查询参数
布局在导航时不会重新渲染,因此它们无法访问搜索参数,否则这些参数会变得过时。
要访问更新后的查询参数,你可以使用 Page 组件的 searchParams prop,或在客户端组件中使用 useSearchParams hook 读取它们。由于客户端组件在导航时会重新渲染,因此它们可以访问最新的查询参数。
TypeScript
'use client'
import { useSearchParams } from 'next/navigation'
export default function Search() {
const searchParams = useSearchParams()
const search = searchParams.get('search')
return '...'
}
import Search from '@/app/ui/search'
export default function Layout({ children }) {
return (
<>
<Search />
{children}
</>
)
}
JavaScript
'use client'
import { useSearchParams } from 'next/navigation'
export default function Search() {
const searchParams = useSearchParams()
const search = searchParams.get('search')
return '...'
}
import Search from '@/app/ui/search'
export default function Layout({ children }) {
return (
<>
<Search />
{children}
</>
)
}
路径名
布局在导航时不会重新渲染,因此它们不会访问路径名,否则路径名会变得过时。
要访问当前路径名,你可以在客户端组件内使用 usePathname Hook 读取它。由于客户端组件在导航期间会重新渲染,因此它们可以访问最新的路径名。
TypeScript
'use client'
import { usePathname } from 'next/navigation'
// Simplified breadcrumbs logic
export default function Breadcrumbs() {
const pathname = usePathname()
const segments = pathname.split('/')
return (
<nav>
{segments.map((segment, index) => (
<span key={index}>
{' > '}
{segment}
</span>
))}
</nav>
)
}
import { Breadcrumbs } from '@/app/ui/Breadcrumbs'
export default function Layout({ children }) {
return (
<>
<Breadcrumbs />
<main>{children}</main>
</>
)
}
JavaScript
'use client'
import { usePathname } from 'next/navigation'
// Simplified breadcrumbs logic
export default function Breadcrumbs() {
const pathname = usePathname()
const segments = pathname.split('/')
return (
<nav>
{segments.map((segment, index) => (
<span key={index}>
{' > '}
{segment}
</span>
))}
</nav>
)
}
import { Breadcrumbs } from '@/app/ui/Breadcrumbs'
export default function Layout({ children }) {
return (
<>
<Breadcrumbs />
<main>{children}</main>
</>
)
}
与 loading.js 的交互
由于 loading.js 位于组件层级中 layout.js 的下方,因此它无法为布局自身中未缓存或运行时的数据访问显示回退内容,例如调用 cookies()、headers(),或进行未缓存的 fetch。
具体行为取决于是否启用了 Cache Components:
- 未启用 Cache Components: 导航会阻塞,直到布局完成渲染,并且不会显示
loading.js回退内容。 - 启用 Cache Components 时:
loading.js会被视为常规的<Suspense>边界,而不是特殊的预取标记。布局中未缓存或运行时的数据访问必须显式包裹在它自己的<Suspense>边界中,否则 Next.js 会通过构建时错误进行提示。静态外壳会立即流式渲染,未缓存的内容会在解析完成后替换进来。
在两种情况下,为确保即时导航,可以任选其一:
- 将布局中的运行时数据访问包裹在它自己的
<Suspense>边界中,并提供回退内容。 - 将未缓存的数据获取从
layout.js移到page.js中,这样loading.js就可以显示回退内容。
TypeScript
import { Suspense } from 'react'
import { NavSkeleton } from './nav-skeleton'
import { DashboardNav } from './dashboard-nav'
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<>
<Suspense fallback={<NavSkeleton />}>
<DashboardNav />
</Suspense>
<main>{children}</main>
</>
)
}
JavaScript
import { Suspense } from 'react'
import { NavSkeleton } from './nav-skeleton'
import { DashboardNav } from './dashboard-nav'
export default function Layout({ children }) {
return (
<>
<Suspense fallback={<NavSkeleton />}>
<DashboardNav />
</Suspense>
<main>{children}</main>
</>
)
}
获取数据
布局无法将数据传递给它的 children。不过,你可以在一个路由中多次获取相同的数据,并使用 React cache 对请求去重,而不会影响性能。
或者,在 Next.js 中使用 fetch 时,请求会自动去重。
TypeScript
export async function getUser(id: string) {
const res = await fetch(`https://.../users/${id}`)
return res.json()
}
import { getUser } from '@/app/lib/data'
import { UserName } from '@/app/ui/user-name'
export default async function Layout({ children }) {
const user = await getUser('1')
return (
<>
<nav>
{/* ... */}
<UserName user={user.name} />
</nav>
{children}
</>
)
}
import { getUser } from '@/app/lib/data'
import { UserName } from '@/app/ui/user-name'
export default async function Page() {
const user = await getUser('1')
return (
<div>
<h1>Welcome {user.name}</h1>
</div>
)
}
JavaScript
import { getUser } from '@/app/lib/data'
import { UserName } from '@/app/ui/user-name'
export default async function Layout({ children }) {
const user = await getUser('1')
return (
<>
<nav>
{/* ... */}
<UserName user={user.name} />
</nav>
{children}
</>
)
}
import { getUser } from '@/app/lib/data'
import { UserName } from '@/app/ui/user-name'
export default async function Page() {
const user = await getUser('1')
return (
<div>
<h1>Welcome {user.name}</h1>
</div>
)
}
访问子路由段
布局无法访问其下方的路由段。要访问所有路由段,你可以在客户端组件中使用 useSelectedLayoutSegment 或 useSelectedLayoutSegments。
TypeScript
'use client'
import Link from 'next/link'
import { useSelectedLayoutSegment } from 'next/navigation'
export default function NavLink({
slug,
children,
}: {
slug: string
children: React.ReactNode
}) {
const segment = useSelectedLayoutSegment()
const isActive = slug === segment
return (
<Link
href={`/blog/${slug}`}
// Change style depending on whether the link is active
style={{ fontWeight: isActive ? 'bold' : 'normal' }}
>
{children}
</Link>
)
}
import { NavLink } from './nav-link'
import getPosts from './get-posts'
export default async function Layout({
children,
}: {
children: React.ReactNode
}) {
const featuredPosts = await getPosts()
return (
<div>
{featuredPosts.map((post) => (
<div key={post.id}>
<NavLink slug={post.slug}>{post.title}</NavLink>
</div>
))}
<div>{children}</div>
</div>
)
}
JavaScript
'use client'
import Link from 'next/link'
import { useSelectedLayoutSegment } from 'next/navigation'
export default function NavLinks({ slug, children }) {
const segment = useSelectedLayoutSegment()
const isActive = slug === segment
return (
<Link
href={`/blog/${slug}`}
style={{ fontWeight: isActive ? 'bold' : 'normal' }}
>
{children}
</Link>
)
}
import { NavLink } from './nav-link'
import getPosts from './get-posts'
export default async function Layout({ children }) {
const featuredPosts = await getPosts()
return (
<div>
{featuredPosts.map((post) => (
<div key={post.id}>
<NavLink slug={post.slug}>{post.title}</NavLink>
</div>
))}
<div>{children}</div>
</div>
)
}
示例
元数据
你可以使用 metadata 对象 或 generateMetadata 函数 修改 <head> HTML 元素,例如 title 和 meta。
TypeScript
import type { Metadata } from 'next'
export const metadata: Metadata = {
title: 'Next.js',
}
export default function Layout({ children }: { children: React.ReactNode }) {
return '...'
}
JavaScript
export const metadata = {
title: 'Next.js',
}
export default function Layout({ children }) {
return '...'
}
须知:
你不应手动向根布局添加
<head>标签,例如<title>和<meta>。而应使用 Metadata APIs,它会自动处理流式渲染以及对<head>元素去重等高级要求。
活动导航链接
你可以使用 usePathname Hook 判断某个导航链接是否处于活动状态。
由于 usePathname 是客户端 Hook,你需要将导航链接提取到一个客户端组件中,然后将其导入到布局中:
TypeScript
'use client'
import { usePathname } from 'next/navigation'
import Link from 'next/link'
export function NavLinks() {
const pathname = usePathname()
return (
<nav>
<Link className={`link ${pathname === '/' ? 'active' : ''}`} href="/">
Home
</Link>
<Link
className={`link ${pathname === '/about' ? 'active' : ''}`}
href="/about"
>
About
</Link>
</nav>
)
}
import { NavLinks } from '@/app/ui/nav-links'
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<NavLinks />
<main>{children}</main>
</body>
</html>
)
}
JavaScript
'use client'
import { usePathname } from 'next/navigation'
import Link from 'next/link'
export function Links() {
const pathname = usePathname()
return (
<nav>
<Link className={`link ${pathname === '/' ? 'active' : ''}`} href="/">
Home
</Link>
<Link
className={`link ${pathname === '/about' ? 'active' : ''}`}
href="/about"
>
About
</Link>
</nav>
)
}
import { NavLinks } from '@/app/ui/nav-links'
export default function Layout({ children }) {
return (
<html lang="en">
<body>
<NavLinks />
<main>{children}</main>
</body>
</html>
)
}
基于 params 显示内容
使用动态路由段,你可以根据 params prop 显示或获取特定内容。
TypeScript
export default async function DashboardLayout({
children,
params,
}: {
children: React.ReactNode
params: Promise<{ team: string }>
}) {
const { team } = await params
return (
<section>
<header>
<h1>Welcome to {team}'s Dashboard</h1>
</header>
<main>{children}</main>
</section>
)
}
JavaScript
export default async function DashboardLayout({ children, params }) {
const { team } = await params
return (
<section>
<header>
<h1>Welcome to {team}'s Dashboard</h1>
</header>
<main>{children}</main>
</section>
)
}
在客户端组件中读取 params
要在客户端组件(不能是 async)中使用 params,你可以使用 React 的 use 函数读取 promise:
TypeScript
'use client'
import { use } from 'react'
export default function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = use(params)
}
JavaScript
'use client'
import { use } from 'react'
export default function Page({ params }) {
const { slug } = use(params)
}
版本历史
| 版本 | 变更 |
|---|---|
v15.0.0-RC |
params 现在是一个 Promise。提供了 codemod。 |
v13.0.0 |
引入了 layout。 |