我有一个从API提取图像的组件。我正在尝试使用react-images
从JSON创建图片库。我在组件中插入JSON,然后将图像数组设置为Gallery组件的道具。我的问题是,在图库组件中,如何使用src
而不是url
将道具中的图像传递到新数组。我相信可以通过在状态中创建数组,然后将props映射到状态来做到这一点,但是我不确定如何做到。
图像组件:
import React, { Component } from 'react';
import Gallery from '../Gallery';
const imageArray = [
{
"ID": 1,
"url": "http://example.com/image1.jpg"
},
{
"ID": 2,
"url": "http://example.com/image2.jpg"
}
]
class Images extends Component {
render() {
return(
<div>
<Gallery images={imageArray} />
</div>
);
}
}
export default Images;
图库组件:
import React, { Component } from 'react';
import Lightbox from 'react-images';
class Gallery extends Component {
constructor(props) {
super(props);
this.state = { images:[] };
}
/* example images[] */
this.setStae({images: [
{ src: 'http://example.com/image1.jpg', width: 4, height: 3 },
{ src: 'http://example.com/image2.jpg', width: 1, height: 1 }
]});
render() {
/* map this.props.images to state */
console.log(this.props.images);
return (
<div>
<Lightbox views={this.state.images}
onClose={this.closeLightbox}
onClickPrev={this.gotoPrevious}
onClickNext={this.gotoNext}
currentImage={this.state.currentImage}
isOpen={this.state.lightboxIsOpen}
/>
</div>
);
};
};
export default Gallery
您可以(并且应该)直接从props
映射图像。这保持了唯一的真理来源。将具有url
属性的图像对象数组映射到具有src
属性的对象数组。
import React, { Component } from 'react';
import Lightbox from 'react-images';
class Gallery extends Component {
render() {
return (
<div>
<Lightbox views={this.props.map(({ url }) => ({ src: url })}
onClose={this.closeLightbox}
onClickPrev={this.gotoPrevious}
onClickNext={this.gotoNext}
currentImage={this.state.currentImage}
isOpen={this.state.lightboxIsOpen}
/>
</div>
);
};
};
export default Gallery