当我使用
layout.tsx
文件在整体根级别更改样式时,它可以工作。
当我在路径级别添加
layout.tsx
文件时,当我在热重载期间进行更改时,会显示更改。
但是当我手动刷新页面,或者停止/启动应用程序,或者
yarn build && yarn start
时,样式就不再存在了。为什么?
使用下一个js版本:
14.2.3
。
此位置的布局文件适用于所有页面的样式。
src
app
(main)
page.tsx
(auth)
login
page.tsx
layout.tsx
但是当我将其定位为如下所示的特定路径时,样式更改仅在热重载期间显示一次。
src
app
(main)
page.tsx
(auth)
login
page.tsx
layout.tsx // adding styles here only shows once during hot reload
register
page.tsx
layout.tsx // adding styles here only shows once during hot reload
layout.tsx // adding styles here only shows once during hot reload
layout.tsx // for testing, no styles here now. Will work if I add styles here.
页面非常基础。
这是根级别的布局文件,始终有效。
import type { Metadata } from "next";
import { Open_Sans } from "next/font/google";
import "./globals.css";
import React from "react";
const font = Open_Sans({ subsets: ["latin"] });
export const metadata: Metadata = {
title: "App",
description: "App description",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={`text-3xl ${font.className}`}>{children}</body>
</html>
);
}
这是仅在第一次热重载期间有效的布局。
(我也尝试复制上面的布局,结果相同)
import React from "react";
const AuthLayout = ({
children,
}: { children: React.ReactNode }) => (
<html lang="en">
<body className="bg-amber-400 text-center mt-4">
{children}
</body>
</html>
);
export default AuthLayout
所有页面组件的内容。唯一的区别是组件的名称。
const LoginPage = () => {
return (
<div>
Login
</div>
);
};
export default LoginPage;
嵌套布局继承上面布局文件的布局。
/layout
/dir/layout <-- inherits the layout from /layout
/dir/subdir/layout <-- inherits the layout from /layout and /dir/layout
每个文档只能有一个 HTML/head/body 元素。如果包含多个实例,您的 DOM 树在生成时将如下所示:
<html>
<body class="...">
<html>
<body class="...">
</body>
</html>
</body>
</html>
如果 DOM 树中存在多个 HTML、head 或 body 标签,浏览器会将它们合并为一个,结果可能和你现在得到的一样出乎意料。
请参阅有关嵌套布局的文档以获取更多信息,并在嵌套布局文件中使用除 HTML/body 或 head 之外的任何其他节点(如简单的
<div>
)。