简体   繁体   English

React Collapsible - 一次打开一个手风琴

[英]React Collapsible - Open One Accordion at time

I am using the Collapsible npm package for React, and it solves most of my tasks, but there is no property that will allow only one active accordion to be opened at a time.我正在为 React 使用 Collapsible npm package,它解决了我的大部分任务,但是没有属性允许一次只打开一个活动的手风琴。 I need logic that will close the previously opened accordion when the user clicks on a new one.我需要在用户单击新的手风琴时关闭先前打开的手风琴的逻辑。 Below is my code of parent and child components.下面是我的父子组件代码。 Any help is welcome.欢迎任何帮助。

Child:孩子:

import Collapsible from 'react-collapsible';

const Accordion = ({
  open,
  trigger,
  triggerWhenOpen,
  children,
}) => {
  return (
    <Collapsible
      open={open}
      lazyRender={true}
      triggerTagName="div"
      trigger={trigger}
      triggerWhenOpen={triggerWhenOpen}
      className="mb-[30px]"
    >
      {children}
    </Collapsible>
  );
};

export default Accordion;

Parent:家长:


 {/*Accordion mapping out */}
              {accordionArray.map((accName) => (
                <Accordion
                  open={accName.open}
                  trigger={accName.trigger}
                  triggerWhenOpen={accName.triggerWhenOpen}
                  key={accName + Math.Random()} //
                >
                  <AccordionContent
                    imgSrc={'/' + accName.imgSrc}
                    imgAlt={accName.imgAlt}
                  />
                </Accordion>
              ))}

You can open one collapsible at a time like this, this worked for me你可以像这样一次打开一个可折叠的,这对我有用

import { useState } from 'react';
import Collapsible from 'react-collapsible';

function App() {
    const [count, setCount] = useState(0);

    return (
        <>
            <Collapsible trigger="Start here" open={count === 1} handleTriggerClick={() => setCount(1)}>
                <p>
                    This is the collapsible content. It can be any element or
                    React component you like.
                </p>
                <p>
                    It can even be another Collapsible component. Check out the
                    next section!
                </p>
            </Collapsible>
            <Collapsible trigger="Start here" open={count === 2} handleTriggerClick={() => setCount(2)}>
                <p>
                    This is the collapsible content. It can be any element or
                    React component you like.
                </p>
                <p>
                    It can even be another Collapsible component. Check out the
                    next section!
                </p>
            </Collapsible>
        </>
    );
}

export default App;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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