javascript - 单击按钮后,Bootstrap5 模态未在 React.js 中显示
问题描述
我正在使用 bootstrap5 进行反应。我在 React 中成功安装了 bootstrap5。现在我必须在我的页面上显示模态,所以我在我的页面上添加了一个按钮和模态代码。
下面是我用于模态的代码。现在我点击按钮然后没有任何工作。我没有得到我的模态。
这里有什么问题?
import React from "react";
function addEmployee(){
return(
<div className="addEmployee">
<button type="button" className="btn btn-primary" data-bs-toggle="modal" data-bs-target="#staticBackdrop">Add Employee</button>
<div className="modal fade" id="staticBackdrop" data-bs-backdrop="static" data-bs-keyboard="false" tabIndex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="staticBackdropLabel">Modal title</h5>
<button type="button" className="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div className="modal-body">
...
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="button" className="btn btn-primary">Understood</button>
</div>
</div>
</div>
</div>
</div>
)
}
export default addEmployee;
解决方案
Bootstrap 5 不再依赖于 jQuery,因此您不需要像react-bootstrap
在 React 中使用 Bootstrap 那样的第三方库。例如,您可以使用data-bs-
标记中的属性,或使用显示/隐藏模式的方法为 Bootstrap 模态创建一个功能组件...
function ModalExample() {
const modalRef = useRef()
const showModal = () => {
const modalEle = modalRef.current
const bsModal = new Modal(modalEle, {
backdrop: 'static',
keyboard: false
})
bsModal.show()
}
const hideModal = () => {
const modalEle = modalRef.current
const bsModal= bootstrap.Modal.getInstance(modalEle)
bsModal.hide()
}
return(
<div className="addEmployee">
<button type="button" className="btn btn-primary" onClick={showModal}>Add Employee</button>
<div className="modal fade" ref={modalRef} tabIndex="-1" >
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title" id="staticBackdropLabel">Modal title</h5>
<button type="button" className="btn-close" onClick={hideModal} aria-label="Close"></button>
</div>
<div className="modal-body">
...
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" onClick={hideModal}>Close</button>
<button type="button" className="btn btn-primary">Understood</button>
</div>
</div>
</div>
</div>
</div>
)
}
推荐阅读
- php - PHP转换多维数组
- postgresql - docker 容器不会在 Amazon Codebuild 上启动 postgres 服务器
- python - 如何在 Pandas 中编写具有其他列条件的聚合函数
- reactjs - 访问 BrowseRouter 的 basename
- c - 使用 NativeCall 在不同平台上处理 C typedef
- r - FactoExtra 包中函数 fviz_pca 中点形状的自定义
- html - 引导轮播,右侧空白
- merge - SAS中的一对多合并(记录不匹配)
- swift - Xcode - SwiftyStoreKit 无效的产品 ID
- spring - 弹簧安全根本不起作用