首页 > 解决方案 > 我想在反应模式中打开点击的图像

问题描述

我读了很多类似的问题,但没有奏效。我想将在图库中单击的对象打开到模态中。我的问题是当用户点击图片打开数组中最后一个对象的模态时。我不知道如何只制作选择打开的模式。

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

标签: react-modal

解决方案


我认为问题出在控制器上。您只有 1 个控制器来显示或隐藏模式。您的渲染功能只能有 1 个模态,例如

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

让我知道它是否有效。


推荐阅读