React调用bootstrap函数

React call bootstrap function?

本文关键字:函数 bootstrap 调用 React      更新时间:2023-09-26

由于某些原因,我不能使用react-bootstrap。所以我想调用bootstrap的函数,如'modal',但它似乎不工作,我得到了这个错误:

modal不是函数

这是我在componentDidMount()中尝试的:

$('#my-modal').modal();

ReactDOM.findDOMNode(this.refs.myModal).modal();

$(this.refs.myModal).modal();

我的模态:

<div class="modal fade" id="my-modal" ref="myModal">
...
</div>

我想知道是否有解决这个问题的方法,或者我必须使用一些库,如'react-bootstrap' ?

谢谢你!

为了确保在调用"modal"函数之前加载bootstrap脚本,我添加了一个按钮:

<button type="button" class="btn btn-default" data-toggle="modal" data-target="#my-modal">Open Modal</button>

当这个按钮被点击时,模态打开。现在,我用onSubmit函数在模态中创建了一个表单

<div class="modal fade" id="my-modal" ref="myModal">
    <form onSubmit={this.testModal}>...</form>
</div>
testModal() {
    // here i tried to call modal('hide') like i did above, but still get the error "modal is not a function"
}

我知道如何解决这个问题了。首先,我需要使jQuery全局(我不知道为什么$不起作用,或者可能是冲突)

import jQuery from 'jquery';
window.jQuery = jQuery;

然后,我需要在我的js文件中要求引导:

require('bootstrap')
// or just require('bootstrap/js/modal'); require('bootstrap/js/transition');

而不是在index.html中包含此脚本:

<script src="/node_modules/bootstrap/dist/js/bootstrap.min.js"></script>

现在,我可以调用

jQuery('#my-modal').modal();

UPDATE:我发现可能有一个问题,如果你不添加jQuery.noConflict(true)在你的构造函数