【发布时间】:2021-07-14 14:01:52
【问题描述】:
我一直想知道解决这个问题的最佳方法是什么,如果我应该使用 For 循环或 Map 遍历数组的元素。
这是我的数组:
templates = [
{
title: "Grocery List",
description: "Description of what this things does so the reader can have info of",
imgURL: "https://res.cloudinary.com/deruwllkv/image/upload/v1625753993/groceries.png",
id: 0,
},
{
title: "Shopping Space",
description: "blablabalblabla",
imgURL: "https://res.cloudinary.com/deruwllkv/image/upload/v1625753766/shopping.png",
id: 1,
},
{
title: "Travel Planning",
description: "blablabalblabla",
imgURL: "https://res.cloudinary.com/deruwllkv/image/upload/v1625753885/travel.png",
id: 2,
},
{
title: "Travel",
description: "blablabalblabla",
imgURL: "https://res.cloudinary.com/deruwllkv/image/upload/v1625753993/groceries.png",
id: 3,
},
];
由映射每个元素的 TemplateList 组件处理。我想将其转换为 For 循环,但我不知道应该如何处理它。另外,在这种情况下使用 For 循环会更好吗?
模板列表:
export type Template = {
title: string;
description: string;
imgURL: string;
id?: number;
};
type Props = {
templates: Template[];
};
const TemplateList = ({ templates }: Props) => {
return (
<div className={styles.scrollContainer}>
{templates.map((item) => (
<TemplateCard
title={item.title}
description={item.description}
img={item.imgURL}
classNameToAdd={styles.cardContainer}
key={item.id}
/>
))}
</div>
);
};
export default TemplateList;
这是我的 TemplateCard 组件:
type Props = {
title: string;
description: string;
img: string;
classNameToAdd?: string;
classNameOnSelected?: string;
};
const TemplateCard = ({ title, description, img, classNameToAdd, classNameOnSelected }: Props) => {
const { aspectRatio, vmin } = useWindowResponsiveValues();
let className = `${styles.card} ${classNameToAdd}`;
const [selected, setSelected] = useState(false);
const handleClick = () => {
setSelected(!selected);
};
if (selected) {
className += `${styles.card} ${classNameToAdd} ${classNameOnSelected}`;
}
return (
<div style={card} className={className} onClick={handleClick}>
<img style={imageSize} src={img}></img>
<div style={cardTitle}>
{title}
{selected ? <BlueCheckIcon style={blueCheck} className={styles.blueCheck} /> : null}
</div>
<div style={descriptionCard}>{description}</div>
</div>
);
};
TemplateCard.defaultProps = {
classNameOnSelected: styles.selected,
};
export default TemplateCard;
【问题讨论】:
-
for 循环根本不返回任何内容。所以即使你想要它也行不通
-
@kevin OP 可以使用 for 循环填充另一个数组并返回该数组。它没有多大意义,我认为可读性较差,但可以做到。
-
那么他仍然需要映射一个数组以生成 jsx,还是我误解了什么? @secan
-
@kevin 一个react组件可以返回一个组件数组并且每个item都会被渲染;你可以在这里看到一个非常简单的例子:jsfiddle.net/95L7nyfe
-
感谢小提琴中的示例。将保持原样。
标签: javascript reactjs typescript loops for-loop