如果你在运行的时候报错:
page.tsx doesn't have a root layout. To fix this error, make sure every page has a root layout.
说明你在使用 App Router(app/
目录)结构 的时候,说明你缺少了一个必须的文件:
你缺了:
app/layout.tsx
正确的 App Router 项目结构(最基本):
app/
├── layout.tsx ← 全局布局(必须)
└── page.tsx ← 首页页面,对应 /
必须添加 layout.tsx
在你的 app/
目录下新建一个 layout.tsx
,比如:
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
你也可以加上 <head>
、导航栏、全局样式等内容。
为什么需要这个文件?
- App Router 是基于“嵌套布局”的思想设计的;
layout.tsx
是所有页面的结构框架(比如公共导航栏、主题、全局样式);- 每个页面都必须被一个 layout 包裹,所以没有这个文件会报错。
最小可运行 App Router 示例
app/
├── layout.tsx ← 必须的根布局
└── page.tsx ← 首页内容
// app/layout.tsx
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
// app/page.tsx
export default function HomePage() {
return <h1>Hello, world!</h1>
}