簡體   English   中英

如何使用 useState 在 React-Bootstrap Accordion 上堅持 state?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM