首页 > 解决方案 > 单击按钮后,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;

标签: javascripthtmlreactjstwitter-bootstrapbootstrap-5

解决方案


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>
    )
}

两种方法的演示


推荐阅读