[英]How to define TypeScript interface for the passed object in props?
Could I get some help please with the definition of an interface for the IconArr.primary
property.我能否就
IconArr.primary
属性的接口定义获得一些帮助。
I am trying to pass it into PrimarySkills
components --> where I have to define interface but without any luck so far.我正在尝试将它传递给
PrimarySkills
组件 --> 我必须在其中定义接口但到目前为止没有任何运气。
I do not want to pass the whole object with both primary and secondary icons, so I can have two separate components but with different input data later.我不想同时传递带有主图标和辅助图标的整个对象,因此我可以有两个单独的组件,但稍后可以使用不同的输入数据。
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>
);
};
in PrimarySkills
Component在
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>
);
};
You can create an interface for each item contained in the array (let's say Icon
), then use it to properly type the iconsArr
prop as an array of that type ( Icon[]
).您可以为数组中包含的每个项目创建一个接口(比如
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>
);
};
Note that because you're passing iconsArr.primary
to the iconsArr
prop, iconsArr
will be an array (it won't have the primary
property).请注意,因为您将
iconsArr.primary
传递给iconsArr
, iconsArr
将是一个数组(它不会具有primary
属性)。 You should map through it using props.iconsArr.map(...)
instead.您应该使用
props.iconsArr.map(...)
来映射它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.