我想向 Next.js 应用程序的某些页面添加持久布局。我找到了 this article解释有关某人如何做到这一点的几种方法。看起来很简单,但是我在使用推荐的方法时遇到了以下两个问题:
as any
:const getLayout =
(Component as any).getLayout ||
((page: NextPage) => <SiteLayout children={page} />);
withApollo
某些页面的 HOC(来自 here)。使用这个会导致 Component.getLayout
永远是 undefined
.我对正在发生的事情没有足够的了解来知道为什么会发生这种情况(我可以猜到),所以我自己很难解决这个问题。 最佳答案
我有类似的问题,这就是我为我的项目解决它的方法。
创建一个 types/page.d.ts
类型定义:
import { NextPage } from 'next'
import { ComponentType, ReactElement, ReactNode } from 'react'
export type Page<P = {}> = NextPage<P> & {
// You can disable whichever you don't need
getLayout?: (page: ReactElement) => ReactNode
layout?: ComponentType
}
在您的 _app.tsx
文件,import type { AppProps } from 'next/app'
import { Fragment } from 'react'
import type { Page } from '../types/page'
// this should give a better typing
type Props = AppProps & {
Component: Page
}
const MyApp = ({ Component, pageProps }: Props) => {
// adjust accordingly if you disabled a layout rendering option
const getLayout = Component.getLayout ?? (page => page)
const Layout = Component.layout ?? Fragment
return (
<Layout>
{getLayout(<Component {...pageProps} />)}
</Layout>
)
// or swap the layout rendering priority
// return getLayout(<Layout><Component {...pageProps} /></Layout>)
}
export default MyApp
以上只是最适合我的用例的示例实现,您可以在 types/page.d.ts
中切换类型以满足您的需求。
关于reactjs - Next.js 中使用 TypeScript 和 HOC 的持久布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62115518/