我想在react mode中打开单击的图像



我读过很多类似的问题,但都不起作用。我想把在图库中点击的对象打开到模态中。我的问题是,当用户点击图片打开数组中最后一个对象的模态时,它被打开了。我不知道如何只打开被选中的模态。

class SingleGallery extends Component{
constructor () {
super();
this.state = {
showModal: false
};

this.handleOpenModal = this.handleOpenModal.bind(this);
this.handleCloseModal = this.handleCloseModal.bind(this);
}

handleOpenModal () {
this.setState({ showModal: true });
}

handleCloseModal () {
this.setState({ showModal: false });
}
render(){
let singleGalleryObj = [
{image: imageGallery1},
{image: imageGallery2},
{image: imageGallery3},
{image: imageGallery4},
{image: imageGallery1},
{image: imageGallery2}
]
return(
<div class="singleGallery">
<div class="SGContent">
<div class="title">Gallery 1</div>
<div class="images">
{singleGalleryObj.map((para) => {
return (
<div>
<div class="galleryBox" onClick={this.handleOpenModal}>
<div class="image">
<img src={para.image} />
</div>
</div>
<Modal 
isOpen={this.state.showModal}
contentLabel="Minimal Modal Example"
>
<button onClick={this.handleCloseModal}>Close Modal</button>
<img src={para.image}/>
</Modal>
</div>

)
})}

</div>
</div>
</div>
)
}
} 

我认为问题出在控制器上。您只有一个控制器来显示或隐藏模态。对于像这样的渲染函数,你只能有一个模态

<div class="singleGallery">
<div class="SGContent">
<div class="title">Gallery 1</div>
<div class="images">
{singleGalleryObj.map((para) => {
return (
<div>
<div class="galleryBox" onClick={() => this.handleOpenModal(para)}>
<div class="image">
<img src={para.image} />
</div>
</div>
</div>

)
})}
<Modal 
isOpen={this.state.showModal}
contentLabel="Minimal Modal Example"
>
<button onClick={this.handleCloseModal}>Close Modal</button>
{this.state.selectedImage ? <img src={selectedImage.image}/> : null}
</Modal>
</div>
</div>
</div>

你的开放模式处理程序可以像一样

handleOpenModal (selectedImage) {
this.setState({ showModal: true, selectedImage });
}

让我知道它是否有效。

最新更新