React 如何解决错误 Type ‘() => JSX.Element[]’ is not assignable to type FunctionComponent

当我们尝试从函数组件返回元素数组时,会发生 React.js 错误“Type ‘() => JSX.Element[]’ is not assignable to type FunctionComponent”。 要解决该错误,需要将元素数组包装到 React 片段中。

React 如何解决错误 Type '() => JSX.Element[]' is not assignable to type FunctionComponent

下面是产生错误的示例代码。

import React from 'react';

// ⛔️ Type '() => JSX.Element[]' is not assignable to type 'FunctionComponent<{}>'.
// Type 'Element[]' is missing the following properties
// from type 'ReactElement<any, any>': type, props, key ts(2322)

const App: React.FunctionComponent = () => {
  return ['Alice', 'jiyik.com'].map(element => <div key={element}>{element}</div>);
};

export default App;

这是完全有效的 React.js 代码,因为我们应该能够从 React 中的函数组件返回一个数组。 但是,FunctionComponent 接口的返回类型是 ReactElement 或 null

这意味着我们只能返回一个 React 元素或一个空值。

为了避免类型错误,我们必须将数组包装到 React 片段中。

import React from 'react';

const App: React.FunctionComponent = () => {
  return (
    <>
      {['Alice', 'jiyik.com'].map(element => (
        <div key={element}>{element}</div>
      ))}
    </>
  );
};

export default App;

当我们需要在不向 DOM 添加额外节点的情况下对元素列表进行分组时,会使用 Fragment 。

我们可能还会看到正在使用的更详细的 Fragment 语法。

import React from 'react';

const App: React.FunctionComponent = () => {
  return (
    <React.Fragment>
      {['Alice', 'jiyik.com'].map(element => (
        <div key={element}>{element}</div>
      ))}
    </React.Fragment>
  );
};

export default App;

上面的两个示例实现了相同的结果——它们对元素列表进行分组,而不向 DOM 添加额外的节点。

另一种解决方案是将元素数组包装在另一个 DOM 元素中,例如 一个 div

import React from 'react';

const App: React.FunctionComponent = () => {
  return (
    <div>
      {['Alice', 'jiyik.com'].map(element => (
        <div key={element}>{element}</div>
      ))}
    </div>
  );
};

export default App;

这仍然符合 FunctionComponent 接口中指定的返回类型,因为我们的组件返回单个 React 元素。