reactjs - 类型 '(props: Props) => Element[]' 不可分配给类型 'FunctionComponent'
问题描述
我正在尝试在 React 应用程序中添加 TypeScript。
版本:
"react": "16.9.0",
"typescript": "3.5.3",
我有一个像
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',
},
];
我通过道具将它传递给组件。
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>
);
});
};
但这给了我错误
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) => {
| ^
我阅读了如何在 typescript 中声明对象数组的答案?,但仍然无法弄清楚如何解决它。
解决方案
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>
)
};
另请注意,您可以使用语法
<>
{ websiteElements }
</>
而不是<React.Fragment>
如果你愿意。
推荐阅读
- css - PrimeFaces Media 组件在操作时调整大小
- php - SQL 错误:mysqli_fetch_assoc() 期望参数 1 为 mysqli_result
- entity-framework - 通用插入多对多(实体框架)
- python - 使用 Python 解析主机名(通过 DNS)
- msbuild - 检测 MsBuild 中 T4 文本转换的任意输入文件更改
- scala - 从 scala spark 文件的第 17 行加载 CSV 文件
- wpf - WPF:根据 Bing 地图的当前比例动态调整网格的大小
- javascript - 自定义可重用
- ibm-mobilefirst - MobileFirst - 如果上传了新版本的 IBM Apps Center,我应该怎么做
- docker - Docker 无法在代理 TLS 握手超时后提取图像