我正在尝试实现一个灵活的灯箱组件来显示图像。我正在使用这个 npm,我从 api 获得的图像 URL。
我应该如何将当前图像索引值传递给(单击哪个图像)组件,以便在模态上显示 adject 图像。
下面是我从后端得到的 JSON
{
"count": 3,
"next": "http://127.0.0.1:8000/api/aws/gallery/all-gallery/?page=2",
"previous": null,
"results": [
{ "id": 127, "gallery_img_url": "https://mysite.amazonaws.com/gallery/test2.jpg" },
{ "id": 126, "gallery_img_url": "https://mysite.amazonaws.com/gallery/CaptureXYZ.PNG" },
{ "id": 125, "gallery_img_url": "https://mysite.amazonaws.com/gallery/Capture2.PNG" }
]
}
onClick 图像我将此 id 从结果数组传递给组件,我认为这可能是问题,有人可以建议我如何将确切的索引值(准确地说,图像点击)传递给组件。
这是我的组件
import React, { Component } from 'react'
import { connect } from 'react-redux';
import { getAllGalleryImages } from '../actions/gallery';
import Lightbox from 'react-image-lightbox';
import 'react-image-lightbox/style.css';
class ViewGalleryImage extends Component {
state = {
photoIndex: 0,
isOpen: false,
}
componentDidMount() {
// this will Fetch data from api
this.props.getAllGalleryImages();
window.scrollTo(0, 0)
}
render() {
const { photoIndex, isOpen } = this.state;
const images = [];
this.props.images && this.props.images.results && this.props.images.results.map(result =>
images.push(result.gallery_img_url),
)
return (
<div>
{this.props.images.count === 0 ? <p><strong>No Images found!</strong></p> :
<React.Fragment>
{this.props.images && this.props.images.results && this.props.images.results.map(result =>
<div className='masonry-item' key={result.id}>
<img src={result.gallery_img_url} onClick={() => this.setState({ isOpen: true, photoIndex: result.id })} alt='myImage' className='dlt_blg_img' />
</div>
)}
</React.Fragment>
}
{
isOpen && (
<Lightbox
mainSrc={images[photoIndex]}
nextSrc={images[(photoIndex + 1) % images.length]}
prevSrc={images[(photoIndex + images.length - 1) % images.length]}
onCloseRequest={() => this.setState({ isOpen: false })}
onMovePrevRequest={() =>
this.setState({
photoIndex: (photoIndex + images.length - 1) % images.length,
})
}
onMoveNextRequest={() =>
this.setState({
photoIndex: (photoIndex + 1) % images.length,
})
}
/>
)
}
</div>
)
}
}
const mapStateToProps = state => ({
isLoading: state.gallery.isLoading,
images: state.gallery
});
export default connect(
mapStateToProps,
{ getAllGalleryImages }
)(ViewGalleryImage);