有没有办法在next.js中实现outlet?在常规反应路由器中,我可以使用 <outlet> 来渲染子组件

问题描述 投票:0回答:2

next.js 或类似中是否有 router Outlet 的实现?我想使用子路由在同一页面上渲染子组件,但我找不到 next.js 具有相同功能的任何内容。

reactjs next.js
2个回答
2
投票

由于您没有使用 Next.js 13+ 的“应用程序目录”,因此没有处理模板/布局的本机方法。相反,您必须创建自己的布局系统

这是一个例子:

// /components/Layout.js
export default function Layout() {
  return (
    <main>
        <header>My Website</header>
        <article>{children}</article>
                {/*  ^ this is your "<Outlet>" */}
    </main>
  )
}
// /pages/blog/post1.jsx
import { Layout } from "@components/Layout";

export default function BlogPost1() {
  return (
    <Layout>
        <h1>Blog post 1!</h1>
    </Layout>
  )
}
// /pages/blog/post2.jsx
import { Layout } from "@components/Layout";

export default function BlogPost2() {
  return (
    <Layout>
        <h1>Blog post 2!</h1>
    </Layout>
  )
}

不要从字面上理解这个例子,在现实场景中,您将使用像

[id].js
这样的动态路由器。


1
投票

你可以使用这样的东西,

应用程序/layout.js

// - Applies to all routes
export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <Header />
        {children}
        <Footer />
      </body>
    </html>
  );
}

应用程序/仪表板/layout.js

// - Applies to route segments in app/dashboard/*
export default function DashboardLayout({ children }) {
  return (
    <>
      <DashboardSidebar />
      {children}
    </>
  );
}

如果你想了解更多,请参考这个:

© www.soinside.com 2019 - 2024. All rights reserved.