REACTJS将变量传递给道具

时间:2018-10-10 16:58:58

标签: javascript reactjs

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>
    ));
  };

我已经过滤掉this.state.brands enter image description here

如您所见,

它具有媒体。我已经过滤了它并映射了具有collection_name ===“ images”

的所有媒体。

enter image description here

以及以下代码行: <div key={i} className="card-img-top"><img src={image.url} onClick={this.props.carouselBrand()}/></div> 我想在onClick函数中传递该图像的子弹值。但是我不知道怎么做,因为我已经过滤了它。如何获得该品牌的子弹?

2 个答案:

答案 0 :(得分:1)

装饰您组成的对象。

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>
));

答案 1 :(得分:0)

您可以将slug附加到新数组中,或者保留带有过滤的media的初始对象的副本。

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