背景:项目封装了全局的layout(导航顶部 以及底部),增加登录注册页面或者其他独立的页面,如何不渲染在全局的layout中?
方案:在_app.js页面中 作多套渲染方案,通过getlayout 属性自定义
应用:独立页面
全局layout
import React, { ReactNode } from 'react'
import Footer from './MyFooter'
import Header from './MyHeader'
import { Layout } from 'antd'
const { Content } = Layout
const MLayout: React.FC<{ children: ReactNode }> = ({ children }) => {
return (
<Layout>
<Header />
<Content>
{children}
</Content>
<Footer />
</Layout>
)
}
export default MLayout
_app.tsx
import '@/styles/reset.css'
import '@/styles/globals.css'
import type { AppProps } from 'next/app'
import 'antd/dist/reset.css';
import MLayout from '../../layout';
import type { NextPage } from 'next'
import type { ReactElement, ReactNode } from 'react'
type NextPageWithLayout = NextPage & {
getLayout?: (page: ReactElement) => ReactNode
}
type AppPropsWithLayout = AppProps & {
Component: NextPageWithLayout
}
export default function App({ Component, pageProps }: AppPropsWithLayout) {
const getLayout = Component.getLayout ?? ((page) => page)
//是否应用页面的自定义layout 如果没有定义 则使用默认的全局layout
//通常定义404 以及登录注册等 独立页面
if (Component.getLayout) return getLayout(<Component {...pageProps} />)
else return <MLayout> <Component {...pageProps} /></MLayout>
}
404 页面
import React, { ReactNode } from 'react'
export default function Index() {
return (
<div>
404
</div>
)
}
Index.getLayout = function getLayout(page: ReactNode) {
return <>{page}</>
}
如果页面中 不增加自定义的getLayout 属性方法的话,就是走全局的layout渲染