首页 > 解决方案 > 我必须单击 2x 或 3x 才能在 React 中关闭手风琴元素

问题描述

我正在尝试为我的网站创建 Accordion 元素,我正在 W3Schools 网站上遵循这些步骤,https: //www.w3schools.com/howto/howto_js_accordion.asp

问题是,当我想关闭手风琴时,我必须单击 2 次才能关闭它,但它会在第一次单击时按预期打开。所以在打开 1 次点击时,在关闭 2 次点击时。我希望它是打开和关闭的 1 单击。

我的 App.js 看起来像这样

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './App.css';

class App extends React.Component {
    render() {

        const myFunction = () => {
            var acc = document.getElementsByClassName("accordion");
            var i;

            for (i = 0; i < acc.length; i++) {
                acc[i].addEventListener("click", function() {
                    this.classList.toggle("active");
                    var panel = this.nextElementSibling;
                    if (panel.style.display === "block") {
                        panel.style.display = "none";
                    } else {
                        panel.style.display = "block";
                    }
                });
            }
        };
        return (
            <div>
                <button className="accordion" onClick={myFunction}>Section 1</button>
                <div className="panel">
                    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit</p>
                </div>
            </div>
        )
    }
}
export default App;
ReactDOM.render(App,document.getElementById("root"));

应用程序.css

.App {
  text-align: center;
}

.App-logo {
  animation: App-logo-spin infinite 20s linear;
  height: 40vmin;
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(10px + 2vmin);
  color: white;
}

.App-link {
  color: #61dafb;
}

@keyframes App-logo-spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* Style the buttons that are used to open and close the accordion panel */
.accordion {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  text-align: left;
  border: none;
  outline: none;
  transition: 0.4s;
}

/* Add a background color to the button if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */
.active, .accordion:hover {
  background-color: #ccc;
}

/* Style the accordion panel. Note: hidden by default */
.panel {
  padding: 0 18px;
  background-color: white;
  display: none;
  overflow: hidden;
}

标签: javascripthtmlreactjs

解决方案


推荐阅读