简体   繁体   English

保持第一个手风琴项目打开

[英]Keep the first accordion item opened

I have a React Js accordion, when i click an item, the panel opens, to close it you have to click the same item or another item, i need the keep the first item opened in the beginning.我有一个 React Js 手风琴,当我点击一个项目时,面板会打开,要关闭它你必须点击同一个项目或另一个项目,我需要在开始时保持第一个项目打开。

The method eventHandler gets the id of each item of the accordion, these items are fetched from an API, everytime i click an item i get the id of the item, but when the component mounts the console.log(active) returns null方法eventHandler获取手风琴每个项目的 id,这些项目是从 API 中获取的,每次我点击一个项目时,我都会获得该项目的 id,但是当组件安装时, console.log(active)返回 null

I need to get the id of the first item, any ideas how to do so?我需要获取第一项的 id,有什么想法可以这样做吗?

Here is my code :这是我的代码:

const { active, setActive } = useContext(AccordionContext)

const eventHandler = (e, index) => {
    e.preventDefault();
    setActive(index !== active ? index : null);
}

return (
    <div id={props.index}>
        <button
            onClick={(e) => eventHandler(e, props.index)}
            aria-expanded={ active === props.index ? 'true' : 'false' }
            aria-disabled={ active === props.index ? 'true' : 'false' }
        >
            <span>
                {props.description}
            </span>
        </button>
        <div>
            <div toggle={active === props.index}></div>
        </div>
    </div>
)

And here is the AccordionContext这是AccordionContext

const AccordionWrapper = (props) => {

    const [active, setActive] = useState(null);

    console.log(active)

    return (
        <AccordionContext.Provider
            value={{
                active, setActive
            }}
        >
            <AccWrapper>
                {props.children}
            </AccWrapper>
        </AccordionContext.Provider>
    )
}

您将null作为active变量的默认值传递,似乎在手风琴中的所有元素都关闭时设置了 null,在useState定义中传递第一个元素索引作为默认值。

useState(0)

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

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