NextJs教程系列(三):路由layout

821 阅读1分钟

可复用的布局

Next.js的layout是一个可复用的布局,不同的子页面可以共享布局容器,页面跳转时,layout容器不会重新渲染。

children props

export default function RootLayout({ children }) {
    return (
        <html lang="en">
            <body>
                <header>头部不会重新渲染</header>
                <main>{children}</main>
                <footer>底部不会重新渲染</footer>
            </body>
        </html>
    )
}

children props是layout的一个参数,它接收一个React元素, 该元素其实就是page.js的渲染结果。

你可以根据你的需求,在layout中添加一些公共的布局元素,比如header, footer等,这些元素不会随着路由的切换而重新渲染。

嵌套布局

layout组件也可以嵌套,例如: layout

app作为最外层的layout,嵌套了dashboard的子layout,dashboard的layout其实对应的就是app中的children。

而dashboard layout.js中的children则对应了dashboard的page页面。

为了方便读者阅读完整的教程,可直接访问作者的教程文档: blog.chdl.fun/ChBlog/docs…