[英]Unable to add new color class to first sub - menu item when outer menu item is opened in accordion
[英]Keep the first accordion item opened
我有一个 React Js 手风琴,当我点击一个项目时,面板会打开,要关闭它你必须点击同一个项目或另一个项目,我需要在开始时保持第一个项目打开。
方法eventHandler获取手风琴每个项目的 id,这些项目是从 API 中获取的,每次我点击一个项目时,我都会获得该项目的 id,但是当组件安装时, console.log(active)返回 null
我需要获取第一项的 id,有什么想法可以这样做吗?
这是我的代码:
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>
)
这是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.