简体   繁体   English

在 React 中将对象作为道具传递的正确方法是什么?

[英]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.我想将图像 URL 的对象作为道具传递给子组件,并在图像组件的 src 属性中使用它。 However I keep getting an error saying that my object key (image1,2 or 3) is undefined.但是,我不断收到错误消息,说我的对象键(image1,2 或 3)未定义。 I tried it without destructuring and the same thing happens.我在没有解构的情况下尝试了它,并且发生了同样的事情。 What am I doing wrong?我究竟做错了什么?

Object with urls带有 url 的对象

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

Parent component (ProjectSection.js)父组件 (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子组件 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.我建议您将一组图像传递给<ProjectPreview />组件。 Then, iterate throught it to display <Image /> component.然后,遍历它以显示<Image />组件。

ProjectSection.js:项目节.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:项目预览.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"} />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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