Next.js 中的持久布局与 TypeScript 和 HOC [英] Persistent layout in Next.js with TypeScript and HOC
问题描述
我想为我的 Next.js 应用程序的某些页面添加持久布局.我发现 这篇文章 解释了几种方法怎么有人能做到这一点.看起来很简单,但是我在使用推荐的方法时遇到了以下两个问题:
I want to add a persistent layout to certain pages of my Next.js application. I found this article explaining a couple ways on how someone could do this. It seems pretty straightforward, however I have encountered the following two problems when using the recommended way of doing it:
- 我正在使用 TypeScript,但不知道如何输入.例如,我有以下工作,但我显然不喜欢使用
as any
:
const getLayout =
(Component as any).getLayout ||
((page: NextPage) => <SiteLayout children={page} />);
- 我正在使用 Apollo,因此我正在使用
withApollo
HOC(来自 这里) 用于某些页面.使用它会导致Component.getLayout
始终为undefined
.我对正在发生的事情没有足够的了解,无法知道为什么会发生这种情况(我可以猜到),所以我自己很难解决这个问题.
- I am using Apollo and so I am using a
withApollo
HOC (from here) for certain pages. Using this causesComponent.getLayout
to always beundefined
. I don't have a good enough understanding of what is going on to know why this is happening (I can guess), so it's difficult to solve this by myself.
推荐答案
我有类似的问题,这就是我为我的项目解决的方法.
I have the similar problem and this is how I solved it for my project.
创建一个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
中切换类型以满足您的需求.
The above is just a sample implementation best suited for my use-case, you can switch the type in types/page.d.ts
to fit your needs.
这篇关于Next.js 中的持久布局与 TypeScript 和 HOC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!