由于某种原因,我无法使用react-bootstrap。所以我想调用 bootstrap 的函数,如“modal”,但它似乎不起作用,我收到了这个错误:
modal is not a function
这是我在 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”?
谢谢!
更新
为了确保在调用“模式”函数之前加载 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 文件中引入 bootstrap:
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();
更新:我发现如果您不在构造函数中添加 jQuery.noConflict(true)
,可能会出现问题。
关于javascript - React调用 Bootstrap 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39216024/