类型 '({ items }: PropsWithChildren<TodoProps>) => Element[]' 不可分配给类型 'FunctionComponent<TodoProps>'

hom*_*rus 15 typescript reactjs react-typescript

我正在学习 Typescript-react,但我陷入了这个错误Type '({ items }: PropsWithChildren<TodoProps>) => Element[]' is not assignable to type 'FunctionComponent<TodoProps>',对此我迷失了。

完全错误:

Type '({ items }: PropsWithChildren<TodoProps>) => Element[]' is not assignable to type 'FunctionComponent<TodoProps>'.
  Type 'Element[]' is missing the following properties from type 'ReactElement<any, string | ((props: any) => ReactElement<any, string | ... | (new (props: any) => Component<any, any, any>)> | null) | (new (props: any) => Component<any, any, any>)>': type, props, key
Run Code Online (Sandbox Code Playgroud)

代码链接:sandbox repo

文件中的TodoList函数声明发生错误TodoList.tsx

任何帮助表示赞赏。干杯!


代码:

import React from "react";

interface Todo {
  id: number;
  content: string;
  completed: boolean;
}

interface TodoProps {
  items: Todo[];
}

//    v------v here is error
const TodoList: React.FC<TodoProps> = ({ items }) => {
  return items.map((item: Todo) => <div key={item.id}>{item.id}</div>);
};

export default TodoList;

Run Code Online (Sandbox Code Playgroud)

for*_*d04 30

是的,这个错误可能听起来有点令人困惑——本质上它是说你只能在函数组件定义中返回一个ReactElement或它的等效项JSX.Element,由React.FC类型强制执行。

React Fragments 解决了这个限制,所以你可以用TodoList 以下方式编写:

interface TodoProps {
  items: Todo[];
}

const TodoList: React.FC<TodoProps> = ({ items }) => (
  <React.Fragment>
    {items.map((item: Todo) => (
      <div key={item.id}>{item.id}</div>
    ))}
  </React.Fragment>
);
Run Code Online (Sandbox Code Playgroud) 简写:
const TodoList: React.FC<TodoProps> = ({ items }) => (
  <>
    {items.map(({ id }) => <div key={id}>{id}</div>)}
  </>
);
Run Code Online (Sandbox Code Playgroud)

顺便说一句:使用纯 JS,类和函数组件都可以返回数组中的多个元素作为渲染输出。目前,TS对函数组件中返回的数组存在类型不兼容,因此 Fragment 在这里提供了一个可行的解决方法(除了类型断言)。

  • 这就是我讨厌TS的原因 (4认同)