我想构建 2 种不同的布局,一种用于我的管理面板,其中包含侧边栏和主要区域,另一种用于我的网站,其中包含页眉、导航栏、主要区域和页脚。我只想要 2 个布局,不想定义每页的布局。在 Next.JS 中是否有任何逻辑可以做到这一点?
最佳答案
在您的 _app.js
中,您可以通过 pageProps
define per page 检查应该使用哪个布局
const App = ({ Component, pageProps }) => {
const getLayout =
pageProps.typeLayout == 'admin' ? ((page) => <AdminLayout children={page} />)
: ((page) => <FrontLayout children={page} />);
return (
<>
{getLayout(<Component {...pageProps} />, pageProps)}
</>
);
};
并且在每个页面中,您应该在 getServerSideProps
中返回 Prop
export const getServerSideProps = async (ctx) => {
return {
props: {
typeLayout : 'admin',
},
};
};
或者您可以通过路由器名称定义布局
const App = ({ Component, pageProps, router }) => {
const getLayout =
router.pathname.includes('/admin') ? ((page) => <AdminLayout children={page} />)
: ((page) => <FrontLayout children={page} />);
return (
<>
{getLayout(<Component {...pageProps} />, pageProps)}
</>
);
};
关于reactjs - 2 种不同的布局 1 用于管理面板,1 用于 Next.JS 中的前端网站?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72709906/