React 中用于图像模态的动态 CSS 类

Dynamic CSS classes in React for image modals

我正在尝试在 React 中制作一个简单的照片库。当我点击照片预览时,我想要弹出一个大图的模式。

到目前为止,我一直在工作。模态元素本身最初设置为 class 和 display: none;。我的问题是,当我单击一张照片时,弹出每个模式。

如何更改一个特定模态元素的 class 名称,以免发生这种情况?

这是我的代码:

import React, { Component } from 'react';
import images from './../data/images';
import './../css/Photos.css';

class Photos extends Component {
  constructor(props) {
    super(props);

    this.state = {
      images: images,
      visible: false,
      //invisibleClass: 'photo-modal-invisible',
      visibleClass: 'photo-modal-invisible'
    };
  }

/*
  Applies the appropriate class for the modal
  when the image is clicked. Class is handled
  in state.
 */

handleClick() {
  const isVisible = this.state.visible;

  if(isVisible === false) {
    this.setState({ visible: true, visibleClass: 'photo-modal-visible' });
  } else {
    this.setState({ visible: false, visibleClass: 'photo-modal-invisible' });
  }
}

  render() {

    var correctClass;

    return(
      <React.Fragment>
      <div className="photo-container">
        {
          this.state.images.map((image, index) =>
            <a onClick={ () => this.handleClick() }><img src={ image.imageSrc } key={ index } /></a>
          )
        }
      </div>
        {
          this.state.images.map(( image, index ) =>
          <div className={ this.state.visibleClass } key={ index }>
            <a href="#" onClick={ () => this.handleClick() }><span class="close">&times;</span></a>
            <img src={ image.imageSrc } />
          </div>
          )
        }
      </React.Fragment>
    );
  }
}

export default Photos;
.photo-container {
  height: 100%;
  width: 100%;
  margin-top: 50px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: flex-start;
}

.photo-container img {
  width: 300px;
  height: 300px;
  margin-right: 30px;
  object-fit: cover;
  filter: grayscale(100%);
  transition: 1s;
}

.photo-container img:hover {
  filter: grayscale(0);
}

.photo-modal-invisible {
  display: none;
}

.photo-modal-visible {
  position: fixed;
  /* stay in place */
  z-index: 1;
  /* sit on top */
  padding-top: 100px;
  /* location of the box */
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  background-color: rgb(0, 0, 0);
  /* fallback color */
  background-color: rgba(0, 0, 0, 0.9);
  /* black with opacity */
}

.photo-modal-visible img {
  margin: auto;
  display: block;
  width: 80%;
  max-width: 700px;
}

.close {
  position: absolute;
  top: 15px;
  right: 35px;
  color: #f1f1f1;
  font-size: 40px;
  font-weight: bold;
  transition: 0.3s;
}

您正在地图函数中的所有图像上设置 class 名称,这就是为什么所有模态图像同时区域 visible/hidden。

在 handleClick 中传递图像的索引并将该索引存储在状态中并使用它来切换模态

为什么不为单个图像创建另一个组件并在单个图像上保持可见状态。因此,当您单击单个图像时,不会影响其他图像状态。