如何使用 useState 在 React-Bootstrap 手风琴上保持状态?
how can I persist state on React-Bootstrap Accordion using useState?
我正在尝试使用 useState 挂钩在 localStorage 中保存 React-Bootstrap 手风琴的状态。
使用 React-Bootstrap docs website 上的示例,我知道我可以获取 eventKey 并使用它来控制它。使用网站上的示例,使用 eventKey 自定义切换按钮与我需要的略有不同,我似乎无法在它们之间实现飞跃。我可以将 eventKey 保存到 localStorage,但无法将其恢复到 eventKey 道具中。
如有任何帮助,我们将不胜感激。
我会利用 <Accordion>
组件 onSelect
道具并传递一个函数,您可以在其中更新 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);
}
}
...
如果您想让此手风琴打开到用户在页面重新呈现时展开的最后一个项目,您可以修改以上内容以实现该行为:
const [expandedItem, setExpandedItem] = useState(localStorage.getItem('expandedItem') ?? "0")
??
就是 Nullish Coalescing Operator.
如果这回答了您的问题,请告诉我。如果这不是您真正想要的,也许您可以使用更多详细信息或代码示例编辑原始 post。
我正在尝试使用 useState 挂钩在 localStorage 中保存 React-Bootstrap 手风琴的状态。
使用 React-Bootstrap docs website 上的示例,我知道我可以获取 eventKey 并使用它来控制它。使用网站上的示例,使用 eventKey 自定义切换按钮与我需要的略有不同,我似乎无法在它们之间实现飞跃。我可以将 eventKey 保存到 localStorage,但无法将其恢复到 eventKey 道具中。
如有任何帮助,我们将不胜感激。
我会利用 <Accordion>
组件 onSelect
道具并传递一个函数,您可以在其中更新 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);
}
}
...
如果您想让此手风琴打开到用户在页面重新呈现时展开的最后一个项目,您可以修改以上内容以实现该行为:
const [expandedItem, setExpandedItem] = useState(localStorage.getItem('expandedItem') ?? "0")
??
就是 Nullish Coalescing Operator.
如果这回答了您的问题,请告诉我。如果这不是您真正想要的,也许您可以使用更多详细信息或代码示例编辑原始 post。