如何在React中关闭Bootstrap 5模态框?
解决React结合Bootstrap 5 CDN模态框更新后无法关闭的问题
问题分析
使用Bootstrap 5 CDN时,模态框的状态由Bootstrap的JavaScript库统一管理,直接通过DOM操作(如修改类名)或React的useRef直接操作元素无法正确触发Bootstrap的模态框关闭逻辑——因为Bootstrap内部维护了模态框的状态和DOM变化流程。
解决方案
通过Bootstrap官方提供的Modal API来关闭模态框,具体修改如下:
在handleSave函数的成功回调中,获取模态框元素并创建Bootstrap Modal实例,调用实例的hide()方法完成关闭:
const handleSave = (event) => { fetch("http://localhost:57030/api/question", { method: "PUT", headers: { Accept: "application/json", "Content-Type": "application/json", }, body: JSON.stringify({ QuestId:qid, ExamUid:exuid, QuestUid:quid, Content:qcont }), }) .then(res => res.json()) .then(res => { console.log(res); refreshList(); // 关闭模态框核心代码 const modalElement = document.getElementById('QuestEditModal'); const modal = new bootstrap.Modal(modalElement); modal.hide(); }, (error) => { alert("Failed" + error); } ); }
为什么之前的方法无效?
useRef仅指向模态框根div时,无法触发Bootstrap初始化时添加的事件监听和内部状态变更,直接操作元素不会生效。- 手动修改DOM类名(如移除
show类)不会触发Bootstrap的模态框关闭事件,可能导致背景遮罩层残留、页面滚动锁定未解除等问题。
内容的提问来源于stack exchange,提问作者Hasan Zubairi
相关产品推荐
相关产品推荐

