布局(layout.js)
layout
文件用于在 Next.js 应用程序中定义布局。
- TypeScript
- JavaScript
app/dashboard/layout.tsx
export default function DashboardLayout({
children,
}: {
children: React.ReactNode
}) {
return <section>{children}</section>
}
app/dashboard/layout.js
export default function DashboardLayout({ children }) {
return <section>{children}</section>
}
根布局是根 app
目录中最顶层的布局。它用于定义 <html>
和 <body>
标签以及其他全局共享的 UI。
- TypeScript
- JavaScript
app/layout.tsx
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
app/layout.js
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
参考
Props
children
(必需)
布局组件应该接受并使用 children
prop。在渲染期间,children
将被填充为布局包装的路由段。这些主要是子布局(如果存在)或页面的组件,但也可能是其他特殊文件,如适用时的加载或错误。
params
(可选)
解析为包含从根段到该布局的动态路由参数对象的 Promise。
- TypeScript
- JavaScript
app/dashboard/[team]/layout.tsx
export default async function Layout({
children
params,
}: {
children: React.ReactNode
params: Promise<{ team: string }>
}) {
const { team } = await params
}
app/dashboard/[team]/layout.js
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'] }> |
- 由于
params
prop 是一个 Promise,你必须使用async/await
或 React 的use
函数来访问值。- 在版本 14 及更早版本中,
params
是一个同步 prop。为了帮助向后兼容,你仍然可以在 Next.js 15 中同步访问它,但此行为将在未来被弃用。
- 在版本 14 及更早版本中,
根布局
app
目录必须包含一个根布局,它是根 app
目录中最顶层的布局。通常,根布局是 app/layout.js
。
- TypeScript
- JavaScript
app/layout.tsx
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
app/layout.js
export default function RootLayout({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
- 根布局必须定义
<html>
和<body>
标签。- 你不应该手动向根布局添加
<head>
标签,如<title>
和<meta>
- 你不应该手动向根布局添加