18

我正在学习 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

代码链接:沙盒回购

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;

4

3 回答 3

36

是的,这个错误可能听起来有点令人困惑——本质上它说你只能在函数组件定义中返回一个ReactElement或它的等价物,由类型强制执行。JSX.ElementReact.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>
);
简写:
const TodoList: React.FC<TodoProps> = ({ items }) => (
  <>
    {items.map(({ id }) => <div key={id}>{id}</div>)}
  </>
);

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

于 2019-11-17T10:38:17.577 回答
4

我遇到了类似的错误。最终,我注意到在使用 TypeScript 将组件转换为 FunctionComponent 时,我错误地将文件从 .js 重命名为 .ts 而不是 .tsx。

于 2020-06-19T17:27:02.230 回答
0

当我试图从我的组件返回children道具时,我也遇到了这个错误,如下所示。Loading


    const { loading, children } = props;
    return loading ? <p>Loading ... </p> : children;

Then i realize that React is expecting only one return value(1 parent component) from its render method. Therefore I wrapped children props with React.Fragment which is denoted by <></> and that solves my problem. Below is my Loadingcomponent sample, hope that helps someone else.

import { FunctionComponent } from "react";

interface ILoadingProps {
  loading: boolean;
}
export const Loading: FunctionComponent<ILoadingProps> = (props) => {
  const { loading, children } = props;
  return loading ? <p>Loading ... </p> : <>{children}</>;
};

于 2021-04-29T15:59:35.700 回答