Qun*_*her 11 node.js next.js next.js13
有没有办法删除 NextJS 13 中特定页面的基本布局?我的大多数视图都有一个通用布局,但其中一些需要单独的布局,我现在找不到任何解决方案。
我尝试在应用程序/根目录下创建具有相同布局的文件夹“组”,但这种方式确实很烦人,并且会破坏项目文件的树状结构。
解决方案 :
答案解决方案很好,但我建议您出于通用目的这样做:
就我个人而言,对于我的项目结构,我需要一条包含布局、标题等的路线,以及另一条根本没有布局的路线。我使用了上面提供的链接,并为我的“根”路线创建了幽灵组。
但是,我还需要标头中的不同内容(包含在布局中),具体取决于我所在的路线。为此,我使用了 LayoutProvider,答案如下,效果很好!
Ali*_*i80 23
NextJS 13实现此目的的方法是使用路由组
简而言之,仅包含所有子级都需要的布局元素,并用于grouping在公共部分共享布局
目录文件结构示例app:
-- (auth)/ # only for grouping, does not add to url
/signin/page.tsx
/singout/page.tsx
/singup/page.tsx
/layout.tsx # shared between auth group only
-- (dashboard)/
/page.tsx # home page
/layout.tsx
-- layout.tsx # main layout, used in ALL pages
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请查看这两个示例项目:
Emr*_*mre 12
当 Next.js <13 时,根布局无法设置为客户端组件。这意味着共享布局在导航期间不会重新呈现。因此,您需要创建一个布局页面,类似于提供程序,可以包装根布局。布局页面必须是客户端组件。
/app: // Use the client directive for using usePathname hook.
'use client'
// Use usePathname for catching route name.
import { usePathname } from 'next/navigation';
export const LayoutProvider = ({ children }) => {
const pathname = usePathname();
return (
<>
{pathname === "/posts" && <h1>Welcome to Posts page!</h1>}
{children}
</>
)
};
Run Code Online (Sandbox Code Playgroud)
/app/layout.js):// Import your layout page
import { LayoutProvider } from './LayoutProvider'
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<LayoutProvider>
{children}
</LayoutProvider>
</body>
</html>
)
}
Run Code Online (Sandbox Code Playgroud)
进一步阅读: