首页 > 解决方案 > 如何使用 useState 在 React-Bootstrap Accordion 上保持状态?

问题描述

我正在尝试使用 useState 挂钩将 React-Bootstrap Accordion 的状态保存在 localStorage 中。

使用 React-Bootstrap文档网站上的示例,我知道我可以获取 eventKey 并使用它来控制它。使用网站上的示例,使用 eventKey 自定义切换按钮与我需要的略有不同,我似乎无法在它们之间进行跳跃。我可以将 eventKey 保存到 localStorage,但无法将其恢复到 eventKey 道具中。

任何帮助,将不胜感激。

标签: javascriptreactjsecmascript-6react-bootstrap

解决方案


我将利用<Accordion>componentsonSelect属性并传递一个函数,您可以在其中更新 Hook 的状态并将该 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

让我知道这是否回答了您的问题。如果这不是您真正想要的,也许您可​​以使用更多详细信息或代码示例编辑您的原始帖子。


推荐阅读