[英]Passing down an array of Objects as props for a React Component
I want to pass down an array of Objects to a child component.我想将一组对象传递给子组件。 Each child component should return the value of the respective index of dummyData.
每个子组件应返回 dummyData 各自索引的值。
Parent Component父组件
export default function MainContent() {
const dummyData = [
{
id: "1",
cardIMG: "test.png",
cardTitle: "Title",
cardText: "Text"
},
{
id: "2",
cardIMG: "test1.png",
cardTitle: "Title",
cardText: "Text"
}
];
return (
<div className="MainContainer">
<Card props={dummyData} />
<Card props={dummyData} />
</div>
);
}
Child Component子组件
export default function Card(props) {
return (
<div className="CardContainer">
<div className="CardIMG">
<img src={this.props.CardIMG} alt="" />
</div>
<div className="TextContent">
<h2>{this.props.CardTitle}</h2>
<p className="TextBlock">{this.props.CardText}</p>
<button className="ReadMore">Read more</button>
</div>
</div>
);
}
Since you are trying to iterate through an array, you have to loop through the items.由于您试图遍历数组,因此必须遍历项目。 You can use
for
, map
or each
, totally upto you.您可以使用
for
、 map
或each
,完全由您决定。
Refer loops: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration参考循环: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration
You can basically do this in your parent component:您基本上可以在父组件中执行此操作:
export default function MainContent() {
const dummyData = [
{
id: "1",
cardIMG: "test.png",
cardTitle: "Title",
cardText: "Text"
},
{
id: "2",
cardIMG: "test1.png",
cardTitle: "Title",
cardText: "Text"
}
];
return (
<div className="MainContainer">
{dummyData.map((data) => {
<Card key={data.id} cardInfo={data} />
})
</div>
);
}
And in your child component(which is a functional component, so you can't use this
in there), you can do在你的子组件中(这是一个功能组件,所以你不能在那里使用
this
),你可以这样做
export default function Card(props) {
return (
<div className="CardContainer">
<div className="CardIMG">
<img src={props.cardInfo.cardIMG} alt="" />
</div>
<div className="TextContent">
<h2>{props.cardInfo.CardTitle}</h2>
<p className="TextBlock">{props.cardInfo.CardText}</p>
<button className="ReadMore">Read more</button>
</div>
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.