![](/img/trans.png)
[英]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.