类型“({articles}: Props) => JSX.Element”不可分配给类型“NextPage<{}, {}>”

Pit*_*nah 16 typescript reactjs tsx next.js

我之前使用过 Vue.js 之后才开始接触 React.js 和 Next.js。我遇到了一个奇怪的打字稿错误,但奇怪的是,尽管 VS Code 向我抱怨它无法编译,但它实际上还是编译了。

我正在尝试将数组Article作为道具传递到我的家庭组件中。

这里是相关代码:

interface Article {
  userId: number;
  id: number;
  title: string;
  body: string;
}

interface Props {
  articles: Article | Article[];
}

const Home: NextPage = ({ articles }: Props) => {
  return (
    <div>
      {/* some stuff */}
    </div>
  );
};
Run Code Online (Sandbox Code Playgroud)

Home带有红色下划线,当我将鼠标悬停在上面时出现错误:

const Home: NextPage<{}, {}>
Type '({ articles }: Props) => JSX.Element' is not assignable to type 'NextPage<{}, {}>'.
  Type '({ articles }: Props) => JSX.Element' is not assignable to type 'FunctionComponent<{}> & { getInitialProps?(context: NextPageContext): {} | Promise<{}>; }'.
    Type '({ articles }: Props) => JSX.Element' is not assignable to type 'FunctionComponent<{}>'.
      Types of parameters '__0' and 'props' are incompatible.
        Property 'articles' is missing in type '{ children?: ReactNode; }' but required in type 'Props'.
Run Code Online (Sandbox Code Playgroud)

任何有关这里可能发生的事情的帮助或见解将不胜感激。

Sai*_*das 39

这样称呼吧

const Home: NextPage<Props> = ({ articles }) => {//your code}
Run Code Online (Sandbox Code Playgroud)

您使用的是 NextPage 类型,我也使用了它。实际上,使用 const Home: NextPage 更好,因为它将输入组件的 props 和返回类型。

  • 它有效,但我不明白为什么。主页在等号之前或函数参数中接收 Props 有何不同? (2认同)

小智 6

你可以这样写:

import React , {FC} from 'react';

interface Article {
  userId: number;
  id: number;
  title: string;
  body: string;
}

interface HomeProps {
  articles: Article[];
}

const Home : FC<HomeProps> = ({articles}) => {

console.log('articles: ', articles)

  return (
    <div>
      {/* some stuff */}
    </div>
  );
};

Run Code Online (Sandbox Code Playgroud)

并在容器中:


const myArticles = [
 {
   userId: 1,
   id: 1,
   title: 'my title',
   body: 'my body',
 }
]
...
return (
 <Home articles={myArticles}>
) 
Run Code Online (Sandbox Code Playgroud)