我有两个文件ListCurses和CardCurses,在ListCurses中有一个对象数组,我试图运行它,并通过props在另一个组件(CardCurses)中显示信息,但是页面返回此错误消息“ TypeError:无法读取未定义“”的属性“ props”。如果有人可以帮助我,我将不胜感激,谢谢!
CardCurses.jsx
import React, { Component } from "react";
import { Card } from "antd";
const { Meta } = Card;
function CardCurses() {
return (
<Card
hoverable
style={{ width: 200, height: 240, padding: "10px" }}
cover={<img alt="example" src={this.props.text.image} />}
>
<Meta
title={this.props.text.title}
description={this.props.text.descricao}
/>
</Card>
);
}
export default CardCurses;
ListCurses
import React from "react";
import Card from "../CardCurses/CardCurses";
function ListCurses() {
const cursos = [
{
title: "React JS",
descricao: "React é legal",
image: "https://pt-br.reactjs.org/logo-og.png"
},
{
title: "React Native",
descricao: "React Native é legal",
image: "https://miro.medium.com/max/1000/1*GkR93AAlILkmE_3QQf88Ug.png"
},
{
title: "Antd",
descricao: "Antd é legal",
image: "https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg"
}
];
const returnCurses = cursos.map((curse, i) => {
return (
<div key={i}>
<Card text={curse} />
</div>
);
});
return <div>{returnCurses}</div>;
}
export default ListCurses;
答案 0 :(得分:1)
您尚未在此处定义任何道具:
function CardCurses() { ... }
您需要:
function CardCurses(props) { ... }
此外,您正在混合函数和类组件。功能组件没有this
。所以:
function CardCurses(props) {
return (
<Card
hoverable
style={{ width: 200, height: 240, padding: "10px" }}
cover={<img alt="example" src={props.text.image} />}
>
<Meta
title={props.text.title}
description={props.text.descricao}
/>
</Card>
);
}
或者:
const CardCurses = ({ text }) => (
<Card
hoverable
style={{ width: 200, height: 240, padding: '10px' }}
cover={<img alt="example" src={text.image} />}>
<Meta title={text.title} description={text.descricao} />
</Card>
);
或者:
const CardCurses = ({ text: { image, title, descricao} }) => (
<Card
hoverable
style={{ width: 200, height: 240, padding: '10px' }}
cover={<img alt="example" src={image} />}>
<Meta title={title} description={descricao} />
</Card>
);
无关的音符。这个
() => { return whatever }
与:
() => whatever
所以您可以:
const returnCurses = cursos.map((curse, i) => (
<div key={i}>
<Card text={curse} />
</div>
));
请注意,索引(i
)并不是一个好的关键字,除了松散的棉绒外,其他任何东西都会对此有所抱怨。如果添加或删除数组中的项目,索引会更改,因此相同的键可能指向不同的项目-不好。
最后,从cursos
中取出ListCurses
。这是一个const并且不会更改,但是您可以在每个渲染器上重新分配它。