簡體   English   中英

React/Typescript 屬性“data”在類型“IntrinsicAttributes & [Interface]”上不存在

[英]React/Typescript Property 'data' does not exist on type 'IntrinsicAttributes & [Interface]'

我創建了一個組件,我在其中訪問本地 json 文件並將對象數組傳遞給另一個組件。

第一個組件的代碼片段 -

導入語句 - import TvData from './Data/TVData.json';

對於第二個組件,我像這樣傳遞數據,我收到此行的錯誤消息

Type '{ data: { id: number; name: string; price: number; imageUrl: string; }[]; }' is not assignable to type 'IntrinsicAttributes & dataProps'.
  Property 'data' does not exist on type 'IntrinsicAttributes & dataProps'.

<SecondComponent data={TvData} />

第二個組件的代碼片段 -

在這里我定義了這樣的接口,

interface dataProp {
    id: number;
    name: string;
    price : number;
    imageUrl : string;
}
type dataProps = dataProp[];

以及帶有這樣參數的功能組件,

function SecondComponent(data: dataProps)

我在其中通過 json 文件中的對象數組進行映射

{
  data.map((item : dataProp) =>
   {
    return (
     <Item key={item.id}>
        {item.name}
      </Item>
           )
    }
  )}

我是 Typescript 的 React 新手,因此我們將不勝感激。

component 道具必須是 object,而不是數組。 嘗試將數組放在其中一個輸入道具中,如下所示:

interface Item {
    id: number;
    name: string;
    price : number;
    imageUrl : string;
}
type Props = { data: Item[] };

...

function SecondComponent(props: Props) {
  return props.data.map(item => (
     <Item key={item.id}>
        {item.name}
      </Item>
    ));
}
    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM