简体   繁体   English

将扩展的 NextPage 类型分配给页面组件时出现类型错误

[英]Type error when assigning extended NextPage type to a page component

I'm getting the type error on const Page as seen in the screenshot and code block below.我在const Page上收到类型错误,如下面的屏幕截图和代码块所示。

在此处输入图像描述

Type '{ (props: Props): JSX.Element; getLayout(page: ReactElement<any, string | JSXElementConstructor<any>>): JSX.Element; }' is not assignable to type 'NextPageWithLayout'.
  Type '{ (props: Props): JSX.Element; getLayout(page: ReactElement<any, string | JSXElementConstructor<any>>): JSX.Element; }' is not assignable to type 'FunctionComponent<{}> & { getInitialProps?(context: NextPageContext): {} | Promise<{}>; } & { getLayout?: ((page: ReactElement<any, string | JSXElementConstructor<...>>) => ReactNode) | undefined; }'.
    Type '{ (props: Props): JSX.Element; getLayout(page: ReactElement<any, string | JSXElementConstructor<any>>): JSX.Element; }' is not assignable to type 'FunctionComponent<{}>'.
      Types of parameters 'props' and 'props' are incompatible.
        Property 'pictures' is missing in type '{}' but required in type 'Props'.ts(2322)
galleryssr.tsx(19, 3): 'pictures' is declared here.

The error is saying that NextPageWithLayout is not accepting getLayout , but that was working fine before I introduced data fetching with getServerSideProps and passed props in as an argument.错误是NextPageWithLayout不接受getLayout ,但在我介绍使用getServerSideProps获取数据并将道具作为参数传入之前,它工作正常。

I think I need to update getLayout or NextPageWithLayout somehow to accept props, but I can't figure out the syntax.我想我需要以某种方式更新getLayoutNextPageWithLayout以接受道具,但我无法弄清楚语法。

NextLayoutWithPage is defined in _app.tsx : NextLayoutWithPage_app.tsx中定义:

export type NextPageWithLayout = NextPage & {
  getLayout?: (page: ReactElement) => ReactNode;
};

type AppPropsWithLayout = AppProps & {
  Component: NextPageWithLayout;
};

function MyApp({ Component, pageProps }: AppPropsWithLayout) {
  const getLayout = Component.getLayout ?? ((page) => page);

  return (
      <ThemeContextProvider>
          {getLayout(<Component {...pageProps} />)}
      </ThemeContextProvider>
  );
}

export default MyApp;

galleryssr.tsx

import type { ReactElement } from "react";
import { SidebarLayout } from "../layouts/SidebarLayout";
import type { NextPageWithLayout } from "./_app";
import Image from "next/image";
import { GetServerSideProps } from "next";

type Picture = {
  id: string;
  author: string;
  width: number;
  height: number;
  url: string;
  download_url: string;
};

// Define type animals which is an array of objects
type Props = {
  pictures: Picture[];
};

const Page: NextPageWithLayout = (props: Props) => {
  return (
    <div className="w-full text-left">
      <h1>This is a server side rendered gallery</h1>
      <div className="grid grid-cols-1 grid-gap-4">
        {props.pictures.map((picture) => {
          return (
            <div
              className="flex flex-col items-center justify-center bg-base-200 p-4 rounded-md my-4"
              key={picture.id}
            >
              <div className="h-[300px] w-[300px] relative">
                <Image
                  src={picture.download_url}
                  alt={picture.id}
                  layout="fill"
                  objectFit="contain"
                  width={picture.width / 20}
                  height={picture.height / 20}
                />
              </div>

              <div>{picture.author}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

Page.getLayout = function getLayout(page: ReactElement) {
  return <SidebarLayout>{page}</SidebarLayout>;
};

// This gets called on every request
export const getServerSideProps: GetServerSideProps = async () => {
  // Fetch data from external API
  const res = await fetch(`https://picsum.photos/v2/list`);
  const pictures = await res.json();
  return { props: { pictures } };
};

export default Page;

In order to make NextPageWithLayout also accept the component's props type you can define an optional generic type that you'll pass down to NextPage .为了使NextPageWithLayout也接受组件的 props 类型,您可以定义一个可选的泛型类型,您将传递给NextPage

export type NextPageWithLayout<P = {}> = NextPage<P> & {
    getLayout?: (page: ReactElement) => ReactNode;
};

You can now define your Page 's type as follows:您现在可以按如下方式定义Page的类型:

type Props = {
    pictures: Picture[];
};

const Page: NextPageWithLayout<Props> = (props) => {
    // Your component's code
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用返回类型为 NextPage 的 function 时出现类型错误 - Type error when using function with the return type NextPage 如何键入高阶 NextPage 组件 - how to type a higher-order NextPage component 对于具有扩展的可区分联合的 React 组件,TypeScript 错误“不可分配给类型‘IntrinsicAttributes’” - TypeScript error "not assignable to type 'IntrinsicAttributes'" for React component with extended discriminated union 使用 TS 类型将字符串分配给 React 组件的 state 时出现 Typescript 错误 - Getting Typescript error when assigning a string to React component's state using TS type "类型 &#39;({ 文章 }: Props) =&gt; JSX.Element&#39; 不可分配给类型 &#39;NextPage&lt;{}, {}&gt;&#39;" - Type '({ articles }: Props) => JSX.Element' is not assignable to type 'NextPage<{}, {}>' TypeScript:从泛型类型分配时属性类型不兼容 - TypeScript: Type of property incompatible when assigning from generic type 当组件是联合类型时如何定义类型 - how to define type when the component is a union type 传入React.Component类型的prop时出现TS错误 - TS error when passing in prop of type React.Component 连接的容器组件中的类型错误 - Type error in connected container component 当使用类型参数定义组件时如何获取组件道具的类型 - How to get type of component props, when component defined with type parameters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM