开发者问题收集

React jQuery 无法将元素识别为 Bootstrap 模式

2018-05-22
122

目标: 在 React 中访问 Bootstrap Modal 的 modal() 代码。

有一个带有 Bootstrap v4 的 React 应用。

package.json

{
  ...
  "dependencies": {
    "bootstrap": "^4.1.1",
    "jquery": "^3.3.1",
    "popper.js": "^1.14.3",
    "react": "^16.3.2",
    "react-dom": "^16.3.2",
    "react-router-dom": "^4.2.2",
    "react-scripts-ts": "2.8.0"
  },
  "scripts": {
    "start": "react-scripts-ts start",
    "build": "react-scripts-ts build",
    "test": "react-scripts-ts test --env=jsdom",
    "eject": "react-scripts-ts eject"
  },
  "devDependencies": {
    "@types/jest": "^22.2.3",
    "@types/node": "^9.6.18",
    "@types/react": "^16.3.14",
    "@types/react-dom": "^16.0.5",
    "@types/react-router-dom": "^4.2.6"
  },
  ...
}

现在尝试通过 Chrome Dev Tools 获取 modal() 得到:

在此处输入图像描述

因此看起来像:

  • 可以 看到 jQuery;
  • 无法 foo Modal 识别为 Bootstrap 的 modal() ;

如何让 jQuery 将 foo 识别为 modal()

1个回答

我不确定我是否理解您的期望。但是如果您想将元素作为引导模式对象获取,则必须至少调用一次模式作为初始化。请查看下面的代码片段:

$('.show-modal-btn').on('click', () => {
  let yourModalEl = $('#your-modal');
  console.log(yourModalEl.data('bs.modal')); // will be undefined
  yourModalEl.modal();
  console.log(yourModalEl.data('bs.modal')); // modal object
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://getbootstrap.com/docs/3.3/dist/js/bootstrap.min.js"></script>
<link href="https://getbootstrap.com/docs/3.3/dist/css/bootstrap.min.css" rel="stylesheet">

<div class="modal fade" id="your-modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">Modal title</h4>
      </div>
      <div class="modal-body">
        <p>One fine body&hellip;</p>
      </div>
    </div>
  </div>
</div>

<button class="show-modal-btn">Init modal</button>
Sakata Gintoki
2018-05-22