Как передать текущий индекс в response-image-lightbox? - PullRequest
0 голосов
/ 14 октября 2019

Я пытаюсь реализовать гибкий компонент лайтбокса для отображения изображений. Я использую этот npm , URL изображения, которые я получаю от API.

Как передать текущее значение индекса изображения компоненту (на каком изображении щелкнули), чтобы отображаемое изображение отображалось в модальном режиме.

Ниже приведен 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 image Я передаю этот идентификатор из массива результатов в компонент, я думаю, что это может быть проблемой, Может кто-то, пожалуйста, подскажите мне, как передать точное значение индекса (точнее, при нажатии на изображение) вкомпонент.

Вот мой компонент

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

1 Ответ

0 голосов
/ 15 октября 2019

Я нашел простое решение для этого. Я думаю, что это может помочь новичку, как я.

Ниже приведена часть обновленного компонента

                <div>
                    {this.props.images.count === 0 ? <p><strong>No Images found!</strong></p> :
                        <React.Fragment>

                    {
                        images.map((index, key) =>
                            <div className='masonry-item' key={key}>

                                <img src={index} alt='gallery' onClick={() => this.setState({ isOpen: true, photoIndex: key })} />
                            </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>
...