gpt4 book ai didi

reactjs - 如何使用 React + TypeScript 通过数组循环渲染组件?

转载 作者:行者123 更新时间:2023-12-05 03:57:24 36 4
gpt4 key购买 nike

我试图循环遍历数组的项目,但我在 TypeScript 中遗漏了我的组件的一些输入。我试过Card<anyCard<IProps>接口(interface)在下面定义(下面未使用)。

这是我目前遇到的错误我收到此错误。

Type '{ key: number; card: { name: string; image: string; id: number; }; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'. Property 'card' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'.

我很想知道我到底缺少什么?

const cards = [
{
name: "a",
image: "red",
id: 1
},
{
name: "b",
image: "blue",
id: 2
},
{
name: "c",
image: "green",
id: 3
}
];

interface IProps {
card: {
name: string;
image: string;
id: number;
};
key: string;
}


...(Stateless component logic here)...

const renderCards = () => {
return cards.map(card => {
return <Card key={card.id} card={card} />;
});
};

return (
<div>

<CardContainer>{renderCards()}</CardContainer>
</div>
);

最佳答案

我需要查看您的 Card 组件实现,但我猜以下内容应该有所帮助:

interface ICard {
name: string;
image: string;
id: number;
}

interface IProps {
card: ICard;
key: string;
}

const cards: ICard[] = [
{
name: "a",
image: "red",
id: 1,
},
{
name: "b",
image: "blue",
id: 2,
},
{
name: "c",
image: "green",
id: 3,
},
];

const Card: React.FC<{ card: ICard }> = ({ card }) => {
return <div>{card.name}</div>;
};

const renderCards = () => {
return cards.map(card => {
return <Card key={card.id} card={card} />;
});
};

return (
<div>
<CardContainer>{renderCards()}</CardContainer>
</div>
);

关于reactjs - 如何使用 React + TypeScript 通过数组循环渲染组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58548531/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com