[英]Clicked accordion not expanding when clicked with React's useState
我有一架手風琴,它可以按我需要的方式工作,除了一件事。 單擊其中一項折疊項后,如果單擊另一個折疊項,則打開的項將關閉,但剛剛單擊的項不會打開。
誰能在我的代碼中發現問題?
const [activeAccordion, setActiveAccordion] = useState(-1);
const handler = (index) => {
setActiveAccordion(currentItem => currentItem === -1 ? index : -1);
};
// relevant section of code below...
{ items.map((e, c) => {
return (
<div key={`key${c}`}>
<button className={styles.accordionButton} onClick={() => handler(c)}>
{e.name}
</button>
{activeAccordion === c &&
<div className={`${styles.accordionContent}`}>
你在handler
有一個小問題。 不是將新項目設置為新打開的項目,而是檢查currentItem === -1
,它會將activeAccordion
設置回-1
(關閉所有手風琴)
對於修復,您可以將其更改為
const handler = (index) => {
const isOpen = index === activeAccordion
setActiveAccordion(isOpen ? -1 : index); //if it's open, we set -1 to close it
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.