[英]Attempt to persist React-Bootstrap Accordion state on localStorage not working
[英]how can I persist state on React-Bootstrap Accordion using useState?
我正在尝试使用 useState 挂钩将 React-Bootstrap Accordion 的 state 保存在 localStorage 中。
使用 React-Bootstrap文档网站上的示例,我知道我可以获取 eventKey 并使用它来控制它。 使用网站上的示例,使用 eventKey 自定义切换按钮与我需要的略有不同,我似乎无法在它们之间进行跳跃。 我可以将 eventKey 保存到 localStorage,但无法将其恢复到 eventKey 道具中。
任何帮助,将不胜感激。
我将使用<Accordion>
组件onSelect
道具并传递一个 function ,您可以在其中更新 Hook 的 state 并将该 eventKey 保存到 localStorage。
const [expandedItem, setExpandedItem] = useState("0")
...
<Accordion
defaultActiveKey={expandedItem}
onSelect={(e) => {
if (e !== null){ // if e === null, that means that an accordion item was collapsed rather than expanded. e will be non-null when an item is expanded
setExpandedItem(e);
localStorage.setItem('expandedItem', e);
}
}
...
如果您想让这个 Accordion 对用户在页面重新呈现时展开的最后一项打开,您可以修改上述内容以实现该行为:
const [expandedItem, setExpandedItem] = useState(localStorage.getItem('expandedItem') ?? "0")
??
是Nullish Coalescing Operator 。
让我知道这是否回答了您的问题。 如果这不是您真正想要的,也许您可以使用更多详细信息或代码示例编辑您的原始帖子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.