在 Next.js 的 App Router (app/
目录结构) 中,layout.tsx
和 page.tsx
是两个核心文件,它们之间有紧密的关系,分别用于定义页面的 布局 和 内容。以下是对它们关系的详细解释:
layout.tsx
<html>
和 <body>
标签。app/
目录下。layout.tsx
可以存在于子目录中,用于覆盖局部布局。children
:这是页面 (page.tsx
) 的内容,会动态传递到布局中。page.tsx
layout.tsx
中。app/
的一个子目录中,例如 app/page.tsx
或 app/dashboard/page.tsx
。page.tsx
文件。page.tsx
是 layout.tsx
的子组件,layout.tsx
使用 children
参数动态渲染 page.tsx
的内容。
layout.tsx
提供框架,page.tsx
填充内容:
layout.tsx
定义了页面的通用框架结构。page.tsx
定义了页面的具体内容。layout.tsx
嵌套,page.tsx
的内容会逐层嵌套在父级布局中。当用户访问某个路径时,Next.js 会自动处理 layout.tsx
和 page.tsx
文件,生成完整的页面:
app/
目录中逐层查找 layout.tsx
文件。page.tsx
内容作为 children
参数传递给最近的布局文件。假设项目目录如下:
textapp/ layout.tsx // 根布局 page.tsx // 首页内容 dashboard/ layout.tsx // Dashboard 局部布局 page.tsx // Dashboard 页面内容 settings/ page.tsx // Dashboard Settings 页面内容
app/layout.tsx
:
tsxexport default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<header>Global Header</header>
<main>{children}</main>
<footer>Global Footer</footer>
</body>
</html>
);
}
app/page.tsx
:
tsxexport default function HomePage() {
return <h1>Welcome to the Home Page!</h1>;
}
访问 /
(根路径) 时:
RootLayout
定义页面的布局框架(<header>
、<footer>
等)。HomePage
的内容(<h1>
)通过 children
插入到 <main>
中。最终渲染的 HTML:
html<html lang="en">
<body>
<header>Global Header</header>
<main>
<h1>Welcome to the Home Page!</h1>
</main>
<footer>Global Footer</footer>
</body>
</html>
app/dashboard/layout.tsx
:
tsxexport default function DashboardLayout({ children }: { children: React.ReactNode }) {
return (
<div>
<aside>Dashboard Sidebar</aside>
<div>{children}</div>
</div>
);
}
app/dashboard/page.tsx
:
tsxexport default function DashboardPage() {
return <h2>Welcome to the Dashboard!</h2>;
}
访问 /dashboard
时:
RootLayout
包裹 DashboardLayout
。DashboardPage
的内容通过 children
插入到 DashboardLayout
。最终渲染的 HTML:
html<html lang="en">
<body>
<header>Global Header</header>
<main>
<div>
<aside>Dashboard Sidebar</aside>
<div>
<h2>Welcome to the Dashboard!</h2>
</div>
</div>
</main>
<footer>Global Footer</footer>
</body>
</html>
app/dashboard/settings/page.tsx
:
tsxexport default function SettingsPage() {
return <p>Here are your settings.</p>;
}
访问 /dashboard/settings
时:
RootLayout
包裹 DashboardLayout
。DashboardLayout
包裹 SettingsPage
的内容。最终渲染的 HTML:
html<html lang="en">
<body>
<header>Global Header</header>
<main>
<div>
<aside>Dashboard Sidebar</aside>
<div>
<p>Here are your settings.</p>
</div>
</div>
</main>
<footer>Global Footer</footer>
</body>
</html>
模块化:
layout.tsx
和 page.tsx
让布局和页面内容解耦,增强代码可维护性。可复用性:
嵌套布局:
性能优化:
layout.tsx
:定义布局框架,用 children
插入子页面内容。page.tsx
:定义具体页面内容,被 layout.tsx
包裹。children
参数连接,形成完整的页面结构。本文作者:空白格
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!