简体   繁体   中英

What is the correct way to pass an object as prop in React?

I want to pass an object of image URL's as a prop to a child component and use it in the src attribute of an image component. However I keep getting an error saying that my object key (image1,2 or 3) is undefined. I tried it without destructuring and the same thing happens. What am I doing wrong?

Object with urls

const imgUrls = {
        image1: '/images/exodevo.webp',
        image2: '/images/njordic.webp',
        image3: '/images/geotechniek.webp',
    }

Parent component (ProjectSection.js)

  <div className="col-md-6 col-lg-4 px-0" data-aos="flip-left">
     <ProjectPreview title={"ExoDevo"} content={"This was a website I built for ExoDevo during my internship at NC-Websites."} techs={"HTML/CSS/JS"} images={{...imgUrls}} website={"https://www.exodevo.com"} />
  </div>

Image component in child component ProjectPreview.js

  <Image
    src={props.images}
    alt={props.title}
    width={335}
    height={210}
  />

I suggest you to pass an array of images into the <ProjectPreview /> component. Then, iterate throught it to display <Image /> component.

ProjectSection.js:

const images = Object.values(imgUrls);

return (
  <div className="col-md-6 col-lg-4 px-0" data-aos="flip-left">
     <ProjectPreview title="ExoDevo" content="This was a website I built for ExoDevo during my internship at NC-Websites." techs="HTML/CSS/JS" images={images} website="https://www.exodevo.com" />
  </div>
);

ProjectPreview.js:

return (
   <>
     {/* Other stuff */}
     {props.images.map((src) => (
        <Image src={src} />
     ))}
   </>
);

I already found out what I was doing wrong. Instead of this:

  <ProjectPreview title={"ExoDevo"} content={"This was a website I built for ExoDevo during my internship at NC-Websites."} techs={"HTML/CSS/JS"} images={{...imgUrls}} website={"https://www.exodevo.com"} />

I should have just done this:

 <ProjectPreview title={"ExoDevo"} content={"This was a website I built for ExoDevo during my internship at NC-Websites."} techs={"HTML/CSS/JS"} {...imgUrls} website={"https://www.exodevo.com"} />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM