簡體   English   中英

如何為 props 中傳遞的對象定義 TypeScript 接口?

[英]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傳遞給iconsArriconsArr將是一個數組(它不會具有primary屬性)。 您應該使用props.iconsArr.map(...)來映射它。

暫無
暫無

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

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