简体   繁体   English

使用 React 的 useState 单击时单击的手风琴未展开

[英]Clicked accordion not expanding when clicked with React's useState

I have an accordion that works the way I need it to, except for one thing.我有一架手风琴,它可以按我需要的方式工作,除了一件事。 After clicking on one of the accordion items, if another one that is collapsed is clicked, the one that was opened will close, but the one that was just clicked will not open.单击其中一项折叠项后,如果单击另一个折叠项,则打开的项将关闭,但刚刚单击的项不会打开。

Can anyone spot the problem in my code?谁能在我的代码中发现问题?

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}`}>

You have a tiny problem in handler .你在handler有一个小问题。 Instead of setting the new item as a newly open one, you check currentItem === -1 , and it will set activeAccordion back to -1 (which closes all accordions)不是将新项目设置为新打开的项目,而是检查currentItem === -1 ,它会将activeAccordion设置回-1 (关闭所有手风琴)

For the fix, you can change it to对于修复,您可以将其更改为

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM