我可以得到一些关于IconArr.primary属性接口定义的帮助吗.

我正在try 将其传递到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>
    );
};

in 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),然后使用它将iconsArrprops 正确地键入为该类型的数组(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(...)来映射它.

Typescript相关问答推荐

类型ElementTypes不可分配给类型ElementTypes.word'

React组件数组及其props 的类型定义

如果我有对象的Typescript类型,如何使用其值的类型?

动态调用类型化函数

为什么TypeScript假设文档对象始终可用?

创建一个根据布尔参数返回类型的异步函数

具有继承的基于类的react 组件:呈现不能分配给基类型中的相同属性

在TypeScrip的数组中判断模式类型

TypeScrip 5.3和5.4-对`Readonly<;[...number[],字符串]>;`的测试版处理:有什么变化?

如何在处理数组时缩小几个派生类实例之间的类型范围?

ApexCharts条形图未显示最小值.负值

尽管对象的类型已声明,但未解析的变量<;变量

根据类型脚本中的泛型属性 Select 类型

对象类型的TypeScrip隐式索引签名

是否可以通过映射类型将函数参数约束为预定义类型?

TypeScrip:从嵌套的对象值创建新类型

为什么我会得到一个;并不是所有的代码路径都返回一个值0;switch 中的所有情况何时返回或抛出?(来自vsCode/TypeScript)

显式推断对象为只读

在类型{}上找不到带有string类型参数的索引签名 - TypeScript

Typescript 从泛型推断类型