6

React报错之Type '() => JSX.Element[]' is not assignable to type FunctionCompo...

 3 years ago
source link: https://www.cnblogs.com/chuckQu/p/16593293.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

React报错之Type '() => JSX.Element[]' is not assignable to type FunctionComponent

正文从这开始~

当我们尝试从函数组件中返回元素组成的数组时,会产生"Type '() => JSX.Element[]' is not assignable to type FunctionComponent"错误。为了解决该错误,可以将元素数组包裹在React片段中。

jsx-element-not-assignable-type-functioncomponent.png

这里有个示例用来展示错误是如何发生的。

// App.tsx
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', 'Bob'].map(element => <div key={element}>{element}</div>);
};

export default App;

这是完全有效的React.js代码,因为我们能够从React的函数组件中返回一个数组。然而,FunctionComponent接口的返回类型是ReactElementnull

这也就意味着,我们可以只返回一个React元素或者null值。

React片段

为了解决该类型错误,我们必须将数组包裹在React片段(React fragment)中。

// App.tsx
import React from 'react';

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

export default App;

当我们需要对一个元素列表进行分组而不向DOM添加额外的节点时,就会用到片段。

React.Fragment

你可能还会看到使用了更加详细的片段语法。

// App.tsx
import React from 'react';

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

export default App;

上面的两个例子达到了相同的结果--它们对元素列表的元素进行分组,而没有给DOM添加额外的节点。

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

// App.tsx
import React from 'react';

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

export default App;

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

为了解决"Type '() => JSX.Element[]' is not assignable to type FunctionComponent"错误,可以使用React片段或者div将元素数组进行包裹。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK