简体   繁体   中英

REACTJS pass a variable into props

galleryItems = () => {
    console.log("brands", this.state.brands)

    var obj = []

    var filteredData = this.state.brands.forEach((item) => {
        var lol = item.media.filter((item2) => item2.collection_name === "images")
        obj = [...obj, ...lol]

    })
    console.log("obj", obj)

    return obj.map((image, i) => (
        <div key={i}  className="card-img-top"><img src={image.url} onClick={this.props.carouselBrand()}/></div>
    ));
  };

I have filtered out this.state.brands 在此处输入图片说明

as you can see, it has media. I have filtered it and mapped all the media that has a collection_name === "images"

在此处输入图片说明

and on this line of code: <div key={i} className="card-img-top"><img src={image.url} onClick={this.props.carouselBrand()}/></div> I want to pass the slug value of that image in the onClick function. But I don't know how because I have already filtered it. How can I get the slug of the brand?

decorate the objects you compose.

var filteredData = this.state.brands.forEach(({media, slug}) => {
  const lol = media.filter(item2 => item2.collection_name === "images").map(image => ({ slug, ...image }));
  obj.push.apply(obj, lol);
})
console.log("obj", obj)

return obj.map((image, i) => (
    <div key={i}  className="card-img-top"><img src={image.url} onClick={() => this.props.carouselBrand(image.slug)}/></div>
));

You could either append slug to your new array, or keep a copy of the initial object with filtered media .

const obj = [].concat(...this.state.brands.map(item =>
               item.media.map(item2 => ({ slug: item.slug, ...item2 }) )
                  .filter(item2 => item2.collection_name === 'images'));

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