React Typescript:类型'X'不能分配给类型'IntrinsicAttributes&{properties}。 TS2322

时间:2020-08-11 13:41:39

标签: reactjs typescript

我正在尝试将道具传递给菜单项组件,但出现imageURL属性错误:

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

似乎imageURL的类型不匹配,但我似乎找不到解决方案。 以下是相关组件:

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;

1 个答案:

答案 0 :(得分:1)

作为菜单项组件,传递的道具只有({ title }:{ title:string })。您需要道具以匹配您在组件中使用的类型。

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>
);