英文:
Is there a way to achieve outlets in next.js ? in regular react router i could use <outlet> to render child components
问题
Next.js 或类似的框架中是否有路由 Outlet 的实现?我想在同一页上使用子路由来渲染子组件,但我还没有找到适用于 Next.js 的相同功能。
英文:
Is there an implementation of router Outlet in next.js or similar ? I want to render child components on the same page using sub-routes, but I haven't been able to find anything for next.js that does the same.
答案1
得分: 1
由于您没有使用Next.js 13+的"app directory",因此没有原生的方式来处理模板/布局。相反,您必须创建自己的布局系统。
以下是一个示例:
// /components/Layout.js
export default function Layout({ children }) {
return (
<main>
<header>My Website</header>
<article>{children}</article>
{/* ^ 这是您的"<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
。
英文:
Since you're not using Next.js 13+'s "app directory" there is no native way of handling templates/layouts. Instead you have to create your own layout system
Here's an example:
// /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>
)
}
Don't take this example literally, in a real-world scenario you would use dynamic router like [id].js
.
答案2
得分: 0
你可以使用类似这样的方式,
<b>app/layout.js</b>
// - 适用于所有路由
export default function RootLayout({ children }) {
return (
<html>
<body>
<Header />
{children}
<Footer />
</body>
</html>
);
}
<b>app/dashboard/layout.js</b>
// - 适用于位于 app/dashboard/* 的路由片段
export default function DashboardLayout({ children }) {
return (
<>
<DashboardSidebar />
{children}
</>
);
}```
参考此链接,
[enter link description here][1][2]
[1]: https://nextjs.org/blog/layouts-rfc
[2]: https://www.youtube.com/watch?v=69-mnojSa0M
<details>
<summary>英文:</summary>
you can use something like this,
<b>app/layout.js</b>
```// Root layout
// - Applies to all routes
export default function RootLayout({ children }) {
return (
<html>
<body>
<Header />
{children}
<Footer />
</body>
</html>
);
}
<b>app/dashboard/layout.js</b>
// - 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
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论