javascript - 从元素中添加和删除活动类
问题描述
当我单击触发转换的不同面板时,我正在尝试添加和删除活动类,因此,如果我单击不同的面板,它会起作用,因为它会触发转换,然后在单击其他面板时结束它,但是如果我想点击一个已经打开和关闭的面板,它不会在第一次点击时再次触发它,而且用户体验不好。我正在用 React 编写它,而且我是初学者,所以也许我做的不对。您可以看到下面的代码,我希望我提供了所有正确的信息。
componentDidMount() {
ReactDom.findDOMNode(this).addEventListener("transitionend", (e) => {
if (
e.propertyName.includes("flex") &&
e.target.classList.contains("open")
) {
e.target.classList.add("open-active");
}
});
ReactDom.findDOMNode(this).addEventListener("click", (e) => {
const elems = document.querySelector(".open-active");
if (elems !== null) {
elems.classList.remove("open-active", "open", "opac");
}
e.target.className = "open-active";
console.log(e);
});
}
render() {
const { index, top, bottom, image, open, onClick } = this.props;
const style = {
backgroundImage: `url(${image})`,
};
const openValue = open ? "open opac" : "";
return (
<div
className={`panel ${openValue}`}
style={style}
onClick={() => {
onClick(index);
}}
>
</div>
和 CSS
.panel > * {
margin: 0;
width: 100%;
transition: transform 0.5s;
flex: 1 0 auto;
display: flex;
justify-content: center;
align-items: center;
}
.panel > *:first-child {
transform: translateY(-100%);
}
.panel.open-active > *:first-child {
transform: translateY(0);
}
.panel > *:last-child {
transform: translateY(100%);
}
.panel.open-active > *:last-child {
transform: translateY(0);
}
.panel p:nth-child(2) {
font-size: 4em;
}
.panel.open {
font-size: 16px;
flex: 5;
}
解决方案
您好,您可以按照以下示例进行操作:
import React, {useState} from "react";
import './styles/style.css'
export default function ShowHideExample() {
const [cssClass, setCssClass] = useState('hide');
return (
<div className="App">
<h2>Show or Hide div</h2>
<button onClick={() => {
(cssClass === 'hide')? setCssClass('show') : setCssClass('hide');
}}>Click me to show or hide the div
</button>
<div className={cssClass}>
<h1>This is dynamically shown</h1>
</div>
</div>
);
}
这是 style.css 文件
.show{
display: block;
background: dodgerblue;
padding:20px;
}
.hide{
display: none;
}
推荐阅读
- ios - 如何使 UIScrollView 可滚动?
- linux - 比较变量和数字
- c# - c# Dapper 中的 dbms_output.Put_line
- ionic-framework - 如何使用离子玻片?
- .net - 为什么要使用 CancellationToken.ThrowIfCancellationRequested?
- c# - SqlParameter:Resharper 的格式字符串中未使用参数
- reactjs - 如何用流描述类属性的类型?
- c# - 给定一个具有相同基类的类型不同的对象列表,一个完全独立的类如何在没有 if/else 逻辑的情况下操作每个对象?
- java - 无法两次读取相同的 InputStream
- php - PHP:SELECT * FROM 的 echo 中的表有问题