如何在 Next.js 中使用 props 输入页面组件?

Dan*_*ich 8 typescript reactjs next.js

我希望正确注释Home函数组件的参数,但遇到了一些麻烦。我希望将其注释为:{ events }: { events: Event[] },但收到 TypeScript 错误,Property 'events' does not exist on type '{ children: ReactNode }' in Next.js

接下来在幕后做了很多魔法,所以我不确定如何解决这个问题。有任何想法吗?

import type { NextPage } from 'next';
import { GetServerSideProps } from 'next';
import axios from '../lib/axios';

import { Event } from '../ts/interfaces';

const Home: NextPage = ({ events }) => {
  return (
    <div>
      {events.map((event: Event) => (
        <div key={event.title}>{event.title}</div>
      ))}
    </div>
  );
};

export const getServerSideProps: GetServerSideProps = async () => {
  const res = await axios.get<Event[]>(`${process.env.API_URL}/events`);

  return {
    props: { events: res.data },
  };
};

export default Home;
Run Code Online (Sandbox Code Playgroud)

jul*_*ves 19

您需要将Homeprops 类型(在您的情况下{ events: Event[] })作为泛型类型传递给NextPage.

import { Event } from '../ts/interfaces';

const Home: NextPage<{ events: Event[] }> = ({ events }) => {
    return (
        <div>
            {events.map((event: Event) => (
                <div key={event.title}>{event.title}</div>
            ))}
        </div>
    );
};
Run Code Online (Sandbox Code Playgroud)

  • @wanna_coder101 奇怪的是,文档中唯一引用“NextPage”的地方在这里:https://nextjs.org/docs/api-reference/data-fetching/get-initial-props#typescript。 (4认同)
  • 有趣的是,官方打字稿示例不包含 NextPage,也不包含如何添加自定义道具类型。 (2认同)

Ded*_*Dev 5

如果有人正在寻找一种“应用程序目录”页面(下一个 13+)。你必须自己制作,我找不到从下一个包导入的类型,所以:

interface IPageProps {
  params: { your_dynamic_prop_here: string };
  searchParams: Record<string | string[], string | undefined>
}
Run Code Online (Sandbox Code Playgroud)
export default function Page(props: IPageProps) {...}
Run Code Online (Sandbox Code Playgroud)