Bootstrap Modal 在 React JS 中不起作用

IT技术 javascript jquery html reactjs twitter-bootstrap-3
2021-05-04 22:51:15

我收到一个错误。我添加了一些代码,并希望在我的代码中了解为什么它不起作用。我不能使用react带。请建议我们是否可以在react中使用 Bootstrap 模式。

我收到一个错误。我添加了一些代码,并希望在我的代码中了解为什么它不起作用。我不能使用react带。请建议我们是否可以在react中使用 Bootstrap 模式。下面是我的代码

import React from 'react';
import $ from 'jquery';
window.jQuery = $;
window.$ = $;
global.jQuery = $;

class Modal extends React.Component {
    constructor(props) {
        super(props);
    }

    componentDidMount() {
        $('#myModal').on('shown.bs.modal', function () {
            $('#myInput').trigger('focus');
        });
    }
    
    render()
    {
        return (
          <div>
             <div className="bd-example">
                 //Button code
                 <button type="button" className="btn btn-primary " data-toggle="modal" data-target="#exampleModalLive">
                Launch demo modal</button>

              //Modal code
              <div className="modal" id="exampleModalLive" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
              <div className="modal-dialog modal-dialog-centered" role="document">
                <div className="modal-content">
                <div className="modal-header">
                    <h5 className="modal-title" id="exampleModalCenterTitle">Modal title</h5>
                    <button type="button" className="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div className="modal-body">
                    ...
                </div>
                <div className="modal-footer">
                    <button type="button" className="btn btn-secondary" data-dismiss="modal">Close</button>
                    <button type="button" className="btn btn-primary">Save changes</button>
                </div>
                </div>
            </div>
            </div>
           </div>
        </div>
    );
  }
}
export default Modal;
3个回答

您可以文件中的文件中包含jquerybootstrap使用CDNindex.htmlpublic

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>

还要确保您已添加bootstrap.css文件,

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">

演示

我认为您还没有在 index.js 文件中导入 bootstrap CSS 和 js。

import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap/dist/js/bootstrap.min.js";

导入这些 CSS 和 js 后它会正常工作

安装 jquery

npm install -S jquery

导入 jquery 和引导程序

import 'jquery/dist/jquery.min.js';

import "bootstrap/dist/css/bootstrap.min.css";
import "bootstrap/dist/js/bootstrap.min.js";