javascript - 我必须单击 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;
}
解决方案
推荐阅读
- python - 创建同义词数据框
- typescript - 将道具传递给设置时的VueJS 3组合API和TypeScript类型问题:类型上不存在属性“用户”
- wordpress - 将收藏夹自定义帖子类型添加到自定义 usermeta 键
- html - 顶部带有文本网格的背景图像
- html - 当我调整它的大小时,如何让我的可调整大小的文本区域不离开我的容器?
- angular - Watir/Selenium - 无法访问注入的 Angular 页面元素
- sql - Why my order by is not sorting correctly using to_char function in a date column?
- flutter - 如何在颤动中延迟导入包
- php - 如何在 Woocommerce 上使用简码或 php 代码向访问者显示会员分配的内容?
- visual-studio-code - 如何将参数添加到自定义 vscode 扩展中的自定义命令?