[英]How to define props interface with passed state/setState values?
[英]How to define TypeScript interface for the passed object in props?
我能否就IconArr.primary
屬性的接口定義獲得一些幫助。
我正在嘗試將它傳遞給PrimarySkills
組件 --> 我必須在其中定義接口但到目前為止沒有任何運氣。
我不想同時傳遞帶有主圖標和輔助圖標的整個對象,因此我可以有兩個單獨的組件,但稍后可以使用不同的輸入數據。
const iconsArr = {
primary: [
{
id: '0',
imgPath: 'images/techIcons/reactjs.svg',
name: 'React',
},
{
id: '1',
imgPath: 'images/techIcons/nextjs.svg',
name: 'NextJS',
},
],
secondary: [
{
id: '0',
imgPath: 'images/techIcons/csharp.svg',
name: 'C#',
},
{
id: '1',
imgPath: 'images/techIcons/java.svg',
name: 'Java',
},
],
};
const Skills = (props: Props) => {
return (
<div>
<StyledCaption contentString='SKILLS'>PRIMARY</StyledCaption>
<PrimarySkills iconsArr={iconsArr.primary} />
</div>
);
};
在PrimarySkills
組件中
interface Props {
iconsArr: {
primary: {
id: string;
imgPath: string;
name: string;
}[];
};
}
const PrimarySkills = (props: Props) => {
return (
<div>
{props.iconsArr.primary.map((icon) => (
<img src={icon.imgPath} alt={icon.name} key={icon.id} height='30' />
))}
</div>
);
};
您可以為數組中包含的每個項目創建一個接口(比如Icon
),然后使用它正確地將iconsArr
鍵入為該類型的數組( Icon[]
)。
interface Icon {
id: string;
imgPath: string;
name: string;
}
interface Props {
iconsArr: Icon[]
}
const PrimarySkills = (props: Props) => {
return (
<div>
{props.iconsArr.map((icon) => (
<img src={icon.imgPath} alt={icon.name} key={icon.id} height='30' />
))}
</div>
);
};
請注意,因為您將iconsArr.primary
傳遞給iconsArr
, iconsArr
將是一個數組(它不會具有primary
屬性)。 您應該使用props.iconsArr.map(...)
來映射它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.