首页 > 解决方案 > 从元素中添加和删除活动类

问题描述

当我单击触发转换的不同面板时,我正在尝试添加和删除活动类,因此,如果我单击不同的面板,它会起作用,因为它会触发转换,然后在单击其他面板时结束它,但是如果我想点击一个已经打开和关闭的面板,它不会在第一次点击时再次触发它,而且用户体验不好。我正在用 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;
}

标签: javascriptreactjscss-transitions

解决方案


您好,您可以按照以下示例进行操作:

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

推荐阅读