簡體   English   中英

如何通過來自 React JS 組件中對象數組的 props 顯示信息

[英]how to display information by props from an array of objects in a component in React JS

我有兩個文件,ListCurses 和 CardCurses,在 ListCurses 中有一個對象數組,我正在嘗試運行它並通過 props 在另一個組件 (CardCurses) 中顯示信息,但頁面返回此錯誤消息“類型錯誤:不能讀取未定義的“道具”屬性。 如果有人可以幫助我,我將不勝感激,謝謝!

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;

你還沒有在這里定義任何道具:

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 之外的任何東西都會抱怨這一點。 如果添加或刪除數組中的項目,索引會發生變化,因此相同的鍵可能指向不同的項目 - 不好。

最后, cursosListCurses 它是一個常量並且不會改變,但您在每次渲染時都會重新分配它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM