当我单击任何手风琴时,每个手风琴都会打开,任何人都可以帮忙吗,我一次只希望打开一个手风琴
const [isActive, setIsActive] = useState(false);
<div className="accordion">
{Object.values(mapped).map((item, index) => (
//{predefined.map(({ date }) => (
<div className="accordion-item">
<div
className="accordion-title"
onClick={() => setIsActive(!isActive)}
>
<div>{item[0].date}</div> <div>11:45</div>
<div>painscale</div>
<div>4</div>
<div>{isActive ? "-" : "+"}</div>
</div>
{isActive && (
<div className="accordion-content">
<table>
<thead>
<tr>
<th>sdcs</th>
</tr>
</thead>
{item.map((e) => {
return (
<tr>
<td> {e.time}</td> <td>{e.d}</td>{" "}
<td> {e.scale}</td> <td>{escale.}</td>
</tr>
);
})}
</table>
</div>
)}
</div>
))}
</div>
当我单击任何手风琴时,每个手风琴都会打开,任何人都可以帮忙吗,我一次只希望打开一个手风琴
这是因为isActive
状态是组件的常规状态,因此将一起控制该组件中的所有其他元素。
但是,要实现所需的目标,您可以将其更改为活动电流指数,如下所示:
const [activeCurrentIndex, setActiveCurrentIndex] = useState();
const toggleShowAccordion = (id) => {
if(activeCurrentIndex === id){
setActiveCurrentIndex();
} else {
setActiveCurrentIndex(id);
}
}
//....
<div className="accordion">
{predefined.map(({ id, date, time , pain_scale, time_stamp})) => (
<div className="accordion-item" key={id}>
<div className="accordion-title" onClick={() => toggleShowAccordion(id)}>
<div>{date}</div>
<div>{isActive ? "-" : "+"}</div>
</div>
{activeCurrentIndex === id && <div className="accordion-content">{time} {pain_scale} {time_stamp}</div>}
</div>
))}
</div>
您将activeCurrentIndex
设置为要展开的手风琴的,并检查 activeCurrentIndex 状态是否与手风琴的 id 相同以展开菜单,否则菜单将关闭。在通过数组映射时,还需要为每个元素提供一个键