首页 > 解决方案 > 列表中的函数仅适用于反应中的第一个列表项

问题描述

我正在遍历一个列表,每个列表项都有一个箭头按钮,可以在它下面显示一个隐藏的 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;
}

标签: javascriptcssreactjs

解决方案


因为您只获得第一个元素的 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)}
...

推荐阅读