javascript - 列表中的函数仅适用于反应中的第一个列表项
问题描述
我正在遍历一个列表,每个列表项都有一个箭头按钮,可以在它下面显示一个隐藏的 div。但是现在每个按钮都会触发列表中的第一项。我现在正在反应,但我找不到正确的解决方案
我的 JS 反应文件
const CardConference = ({ content }) => {
const showItems = () => {
const items = document.getElementsByClassName("hidden-items")[0];
const arrow = document.getElementsByClassName("arrow-down")[0]
if (items.style.display == "block") {
items.style.display = "none";
arrow.classList.toggle('rotate-arrow')
} else {
items.style.display = "block";
arrow.classList.toggle('rotate-arrow')
}
}
return (
<div className="card card-conferences ">
<h4> {content[0].title} </h4>
<ul>
{content[0].cities.map((city) => (
<div>
<li className="city-name"> {city.name}
<button className="btn button-arrow" onClick={showItems} ><FaAngleDown color="#717171" className="arrow-down" /></button>
</li>
<ul className="hidden-items">
{city.conferenties.map((conf) => (
<li className="hidden-item">{conf} </li>
))}
</ul>
</div>
))}
</ul>
</div >
);
}
export default CardConference;
这是我的CSS
.arrow-down {
position: absolute;
margin-top: -11px;
margin-left: -6px;
transition: transform 1s;
}
.rotate-arrow {
transform: rotate(180deg);
}
..hidden-items {
display: none;
}
解决方案
因为您只获得第一个元素的 getElementsByClassName 。您需要传递一个索引才能准确获取元素。
const showItems = (i) => () => {
const items = document.getElementsByClassName("hidden-items")[i];
const arrow = document.getElementsByClassName("arrow-down")[i]
...
cities.map((city, index)
...
onClick={showItems(index)}
...
推荐阅读
- javascript - Angular 应用程序无法识别 StencilJs 自定义 Web 组件的全局样式
- encoding - DBI(数据总线反转)是否保存熵?
- python - 如何解决这个显示正确输出的问题?
- gatsby - 动态引用不在 Gatsby 中的静态目录中的图像
- php - npm - 主错误,未找到模块 - 新的 laravel (8) 应用程序
- postgresql - Postgres:如何将 JSONB 值转换为数字
- sql - SQL 按唯一值过滤文本字符串
- oracle - 为什么命令 conn / as sysdba 在 sqlplus 中抛出错误?
- javascript - 调度拖尾事件
- sql - 无法解决错误消息 Msg 241, Level 16, State 1, Line 1 从字符串转换日期和/或时间时转换失败