我有两个文件,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;
列表诅咒
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;
最佳答案
你还没有在这里定义任何 Prop :
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
) 不是一个好的键,除了松散的 linter 之外的任何东西都会提示这一点。如果添加或删除数组中的项目,索引会发生变化,因此同一个键可能引用不同的项目 - 这不好。
最后,从ListCurses
中取出cursos
。它是一个 const 并且不会改变,但您可以在每次渲染时重新分配它。
关于javascript - 如何在 React JS 的组件中通过 props 显示信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59295415/