有办法在next.js中实现outlets吗?在常规React路由器中,我可以使用它< outlet>来呈现子组件

dba5bblo  于 2023-08-04  发布在  React
关注(0)|答案(2)|浏览(158)

在next.js中是否有路由器Outlet的实现或类似的实现?我想在同一个页面上使用子路由呈现子组件,但是我还没有找到任何next.js可以做同样的事情。

7vhp5slm

7vhp5slm1#

因为你没有使用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这样的动态路由器。

3xiyfsfu

3xiyfsfu2#

你可以用这个

app/layout.js

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

字符串

app/dashboard/layout.js

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

refer this,

[enter link description here][1][2]

  [1]: https://nextjs.org/blog/layouts-rfc
  [2]: https://www.youtube.com/watch?v=69-mnojSa0M

相关问题