javascript - 如何使用 useState 在 React-Bootstrap Accordion 上保持状态?
问题描述
我正在尝试使用 useState 挂钩将 React-Bootstrap Accordion 的状态保存在 localStorage 中。
使用 React-Bootstrap文档网站上的示例,我知道我可以获取 eventKey 并使用它来控制它。使用网站上的示例,使用 eventKey 自定义切换按钮与我需要的略有不同,我似乎无法在它们之间进行跳跃。我可以将 eventKey 保存到 localStorage,但无法将其恢复到 eventKey 道具中。
任何帮助,将不胜感激。
解决方案
我将利用<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。
让我知道这是否回答了您的问题。如果这不是您真正想要的,也许您可以使用更多详细信息或代码示例编辑您的原始帖子。
推荐阅读
- c# - 如何重写泛型类型的函数?
- boost - 有没有办法订阅和收听 boost beast websocket 中的提要?
- regex - 正则表达式不够懒惰
- pandas - 在 Pandas 中处理庞大的数据集时,排序是否会降低计算成本?
- regex - tcl 正则表达式提取字符串开头部分的问题
- php - Eloquent / Laravel 8:雄辩的请求不会将想要的值存储到 $variable
- python - 使用 URL 从服务器获取文件。(DJANGO)
- authentication - 对一个特定端点使用不同的授权,.net 核心
- javascript - Material UI:将 Tab 子元素包装在 div 元素中
- ansible-2.x - 在 Ansible 任务中使用 lineinfile 和成为:是的权限被拒绝