首页 > 解决方案 > 实际上无法在反应中访问第二个对象

问题描述

import React from 'react';

import Card from "./Card.jsx";
import contacts from "./contacts";

function App(){

    return(<div>
        <h1 className="Heading">My contacts</h1>
        <Card name={contacts[0].name}
           img={contacts[0].imgURL}
          tel=  {contacts[0].phone}
          email={contacts[0].email}
         />
         <Card name={contacts[1].name}
           img={contacts[1].imgURL}
          tel=  {contacts[1].phone}
          email={contacts[1].email}
         />
          
    </div>);
}
  export default App;

const contacts=[
    {
        id:0,
        name:"Siya",
        imgURL:"https://images.unsplash.com/photo-1593504891806-cc4c04398e7c?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
        phone:"+556666565",
        email:"p@beyonce"
    
    },
    {
        id:1,
        name:"Riya",
        imgURL:"https://images.unsplash.com/photo-1594638739414-f21af9a25dba?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=500&q=60",
        phone:"+556666565",
        email:"p@beyonce"
    
    },
    
];
export default contacts;

在此处输入图像描述

在此处输入图像描述

标签: reactjs

解决方案


嗨,您为什么不尝试像这样迭代常量,根据您的要求更改 HTML 标记。但这对你有用

    const cards= contacts.map((item, index) =>
      <div key={index}>
            <Card name={item.name}
                  img={item.imgURL}
                  tel=  {item.phone}
                  email={item.email}
            />
      </div>
      );

然后在你的回报尝试

    return (
      <React.Fragment>
          <div>
          <h1 className="Heading">My contacts</h1>
          <div>{cards}</div>
      </React.Fragment>
    );

推荐阅读