类型 '(props: Props) => Element[]' 不可分配给类型 'FunctionComponent<Props>'

Hon*_*iao 18 typescript reactjs

我正在尝试在 React 应用程序中添加 TypeScript。

版本:

"react": "16.9.0",
"typescript": "3.5.3",
Run Code Online (Sandbox Code Playgroud)

我有一个像

import aLogo from '../images/a.svg';
import bLogo from '../images/b.svg';

const websites = [
  {
    name: 'A',
    src: aLogo,
    url: 'https://a.com',
  },
  {
    name: 'B',
    src: bLogo,
    url: 'https://b.com',
  },
];
Run Code Online (Sandbox Code Playgroud)

我通过道具将它传递给一个组件。

interface Website {
  name: string;
  src: string;
  url: string;
}

interface Props {
  websites: Website[];
}

const SocialList: React.FC<Props> = (props: Props) => {
  const { websites } = props;

  return websites.map((website) => {
    const { name, src, url } = website;

    return (
      <a key={name} href={url}>
        <img src={src} />
      </a>
    );
  });
};
Run Code Online (Sandbox Code Playgroud)

但它给了我错误

TypeScript error in /SocialList.tsx(16,7):
Type '(props: Props) => Element[]' is not assignable to type 'FunctionComponent<Props>'.
  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  TS2322

    14 | }
    15 | 
  > 16 | const SocialList: React.FC<Props> = (props: Props) => {
       |       ^
Run Code Online (Sandbox Code Playgroud)

我阅读了如何在打字稿中声明对象数组的答案,但仍然无法弄清楚如何修复它。

Hen*_*ody 47

React 组件不能以数组的形式呈现(或返回功能组件),而这正是你目前所拥有的。您可以更新您的代码以返回 a 中的a标签React.Fragment,这基本上是您所追求的,但被允许。

例子:

const SocialList: React.FC<Props> = (props: Props) => {
  const { websites } = props;

  const websiteElements = websites.map((website) => {
    const { name, src, url } = website;

    return (
      <a key={name} href={url}>
        <img src={src} />
      </a>
    );
  });

  return (
    <React.Fragment>
      { websiteElements }
    </React.Fragment>
  )
};
Run Code Online (Sandbox Code Playgroud)

另请注意,您可以使用语法

<>
  { websiteElements }
</>
Run Code Online (Sandbox Code Playgroud)

而不是<React.Fragment>如果你愿意。


Asa*_*viv 9

该错误是关于返回一个 JSX 元素数组,该数组不是来自组件的有效返回类型。

您必须返回一个节点,您所要做的就是将它包装在一个片段<></><div></div>等等中......

你也不需要props再次输入参数

const SocialList: React.FC<Props> = ({ websites }) => (
  <>
    {websites.map(({ name, src, url }) => (
      <a key={name} href={url}>
        <img src={src} />
      </a>
    ))}
  </>
);
Run Code Online (Sandbox Code Playgroud)


Dim*_*nis 7

由于您收到此错误的原因,此处接受的答案不正确。从 React v16 开始,React 组件可以返回包含 React 元素的数组。不必返回 Fragment。

这是 React types 包的问题,​​更具体地说是 TS 本身的问题。

来源 1 来源 2

作为解决方法,您可以抑制此错误消息,因为它本身就是错误的,或者实际上返回一个 Fragment

  • 您可以在引发 TS 错误的行上方添加行 // @ts-ignore。这样做是安全的,因为这不是 React 中的实际错误。 (2认同)