2 回答

TA貢獻(xiàn)1839條經(jīng)驗(yàn) 獲得超15個(gè)贊
創(chuàng)建單獨(dú)的組件來保持“打開”狀態(tài)。像這樣的東西..
function QuestionAnswer({post}) {
const [open1, setOpen1] = useState(true);
return (
<>
<div
className="questionrectangle "
onClick={() => setOpen1(!open1)}
name="step-one"
aria-controls="example-collapse-text"
aria-expanded={open1}
>
<p className="questiontext "> {post.QString}</p>
</div>
{open1 && (
<div name="step-two">
<p className="questionanswer">{post.Answer}</p>
</div>
)}
</>
);
}
現(xiàn)在,從您的主應(yīng)用程序中獲取數(shù)據(jù)并為每個(gè)帖子創(chuàng)建一個(gè)組件 - 就像這樣
// Replace this with fetch request
const data = [
{ QString: "Question 1", Answer: "answer 1" },
{ QString: "Question 2", Answer: "answer 2" },
{ QString: "Question 3", Answer: "answer 3" }
];
return (
<Container fluid={true} className="text-center">
{data.map((post) => (
<QuestionAnswer post={post} />
))}
</Container>
);
}
現(xiàn)在,每個(gè)組件將保存自己的“打開”狀態(tài)副本,并且能夠處理單獨(dú)的打開和關(guān)閉狀態(tài)。
您可以查看完整的示例
https://codesandbox.io/s/beautiful-surf-ejron

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個(gè)贊
思考這個(gè)問題的技巧是,每個(gè)子元素(您的 <Containers /> 列表)不應(yīng)該負(fù)責(zé)了解它們的兄弟元素,或者如何負(fù)責(zé)任地管理它們之間的打開狀態(tài)而不引起沖突。這種責(zé)任應(yīng)該更高一個(gè)層次,能夠看到所有的孩子并為他們管理。
應(yīng)該很容易采用該手風(fēng)琴示例供您自己使用。
const DocsManager = () => {
// Manage which step is open here, at a higher level
const [openIndex, setOpenIndex] = useState(0); // or whatever the default should be
// Records could live here, or be passed in as props
const [docs, setDocs] = useState([]);
useEffect(() => {
getDocs.then(setDocs);
}, [])
return docs.map((doc, i) =>
<YourComponent
isOpen={openIndex === i}
// Or maybe
open={() => setOpenIndex(i)}
// Or maybe
close={() => setOpenIndex(null)}
// Or maybe
next={() => setOpenIndex(openIndex + 1)}
doc={doc}
/>
);
};
添加回答
舉報(bào)