首页 > 解决方案 > Bootstrap modal 不能在 React 打字稿应用程序中工作,但在小提琴上工作

问题描述

根据我目前的研究:

这是一个调试版本https://preprod-ansaar.web.app/

我在我的中实现了一个引导模式app.tsx

import React from 'react';
const app: React.FC = () => {
  return (
    <div>
      <button id="btn1">Show Modal</button>
      <br />
      <button data-onclick="alert('Button Clicked')">Another Button</button>


      <div className="modal fade" id="myModal" data-tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div className="modal-dialog" role="document">
          <div className="modal-content">
            <div className="modal-header">
              <button className="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 className="modal-title" id="myModalLabel">Modal Title</h4>
            </div>
            <div className="modal-body">
              Modal Body
      </div>
            <div className="modal-footer">
              <button className="btn btn-default" data-dismiss="modal">Close</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

export default app;

index.css的是:

#myModal {
  position: relative;
}

.modal-dialog {
  position: fixed;
  width: 100%;
  margin: 0;
  padding: 10px;
}

index.html我有:

  <script>
    $('#btn1').click(function () {
      // reset modal if it isn't visible
      if (!($('.modal.in').length)) {
        $('.modal-dialog').css({
          top: 0,
          left: 0
        });
      }
      $('#myModal').modal({
        backdrop: false,
        show: true
      });

      $('.modal-dialog').draggable({
        handle: ".modal-header"
      });
    });
  </script>

相同的代码正在生成一个可拖动的模式,同时保持背景在小提琴上可用

这在我的 React 应用程序中不起作用,有人可以指导吗?

标签: javascriptjqueryreactjstwitter-bootstraptypescript

解决方案


正如@nithin评论中所建议的那样, 点击处理程序在DOM准备好之前就注册了,这使得它变得多余。尝试将点击处理程序移动到componentDidMount.

componentDidMount() {    
    //modal logic goes here    
}

并且小提琴有效,因为DOM在脚本执行之前已经初始化(因为你没有在那里使用反应)


推荐阅读