gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:39:31 25 4
gpt4 key购买 nike

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

到目前为止,我已经完成了这项工作。模态元素本身最初设置为带有 display: none; 的类。我的问题是,当我点击一张照片时,弹出每个模式。

我怎样才能更改一个特定模态元素的类名,以免发生这种情况?

这是我的代码:

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

最佳答案

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

关于javascript - React 中用于图像模态的动态 CSS 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53952523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com