reactjs - React Typescript: Type 'X' is not assignable to type 'IntrinsicAttributes & { properties }. TS2322
问题描述
I'm trying to pass a prop to a menu item component but I get this error with the imageURL attribute:
Type '{ key: number; title: string; imageURL: string; }' is not assignable to type 'IntrinsicAttributes & { title: string; }'.
Property 'imageURL' does not exist on type 'IntrinsicAttributes & { title: string; }'. TS2322
It looks like there is a type mismatch for imageURL but I can't seem to find the solution. Here are the relevant components:
MenuItem.tsx
import React from 'react';
import './MenuItem.scss'
const MenuItem = ({ title }:{ title:string }) => (
<div className='menu-item'>
<div className='content'>
<h1 className='title'>{title}</h1>
<span className='subtitle'>SHOP NOW</span>
</div>
</div>
);
export default MenuItem;
Directory.tsx
import React from 'react';
import './Directory.scss';
import MenuItem from '../menuItem/MenuItem';
type MenuItems = {
title:string;
imageURL:string;
id:number
};
class Directory extends React.Component<Object, any> {
constructor(props:object) {
super(props);
this.state = {
sections: [
{
title: 'category1',
imageURL: 'https://website1.com',
id: 1
},
{
title: 'category2',
imageURL: 'https://website2.com',
id: 2
},
{
...
}
]
};
};
render() {
return (
<div className='directory-menu'>
{
this.state.sections.map(({ title, imageURL, id }:MenuItems) => (
<MenuItem key={id} title={title} imageURL={imageURL} />
))
}
</div>
);
};
};
export default Directory;
解决方案
您就像({ title }:{ title:string })
为您传递的道具一样是 MenuItem 组件。您需要道具与您在组件中使用的类型相匹配。
这个
const MenuItem = ({ title }:{ title:string }) => (
<div className='menu-item'>
<div className='content'>
<h1 className='title'>{title}</h1>
<span className='subtitle'>SHOP NOW</span>
</div>
</div>
);
应该
const MenuItem = ({ title,imageURL }:{ title:string;mageURL:string }) => (
<div className='menu-item'>
<div className='content'>
<h1 className='title'>{ title }</h1>
<span className='subtitle'>SHOP NOW</span>
</div>
</div>
);
推荐阅读
- powershell - 在 PowerShell 上使用 Get-Content 时使用变量作为 -path
- python - pandas groupby 获取列的聚合并将大小分组到数据框中
- c++ - 从不同文件中使用 sfinae 的正确方法是什么?
- reactjs - ReactJS 中的继承
- c# - 将行设置为 TableFooterView
- javascript - 如何链接 JSON 文件,以便对其进行解析并用于创建数组列表
- openstreetmap - 使用正确的印度地图打开街道地图服务器
- amazon-web-services - AWS SAM:java8/gradle 应用程序在部署时因 ClassNotFound 而失败(但在本地运行良好)
- flowtype - 流不相交联合检查适用于文字字符串,但不适用于常量
- swiftui - SwiftUI - 带列表的段控制