【发布时间】:2020-11-24 08:34:18
【问题描述】:
我想创建类似于手风琴的东西: https://codesandbox.io/s/suspicious-golick-xrvt5?file=/src/App.js
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const items = [
{
title: "lorem1",
content: "content1"
},
{
title: "lorem2",
content: "content2"
}
];
const [hide, setHide] = useState({
title: "",
open: false
});
const hideContent = (title) => {
setHide({
title: title,
open: !hide.open
});
};
return (
<div className="App">
{items.map((i) => {
return (
<div>
<h1 onClick={() => hideContent(i.title)}>{i.title}</h1>
{hide.title === i.title && hide.open ? <p>{i.content}</p> : ""}
</div>
);
})}
</div>
);
}
现在,当我单击一个标题时,它的内容会出现,但是当单击另一个标题时,第一个内容会消失,但实际点击的内容不会出现。如何点击第二个标题隐藏之前的内容,同时打开实际点击的item内容?
【问题讨论】:
-
您需要删除
hide.open才能打开点击内容,即{hide.title === i.title ? <p>{i.content}</p> : ""} -
@ShubhamVerma,但这样我无法关闭所有项目
-
@ShubhamVerma,你知道另一种解决方案吗?
-
是的,答案已更新
标签: reactjs react-hooks