React 错误 Type ‘() => JSX.Element[]’ is not assignable to type FunctionComponent
当我们尝试从函数组件返回元素数组时,会发生 React.js 错误“Type ‘() => JSX.Element[]’ is not assignable to type FunctionComponent”。 要解决该错误,需要将元素数组包装到 React 片段中。
下面是错误发生的示例。
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 接口的返回类型是 ReactElement 或 null。
这意味着我们只能返回一个 React 元素或一个空值。
为了避免类型错误,我们必须将数组封装到 React 片段中
import React from 'react';
const App: React.FunctionComponent = () => {
return (
<>
{['Alice', 'Bob'].map(element => (
<div key={element}>{element}</div>
))}
</>
);
};
export default App;
当我们需要在不向 DOM 添加额外节点的情况下对元素列表进行分组时,会使用片段。
我们可能还会看到正在使用的更详细的片段语法。
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
。
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 元素。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。