【问题标题】:Bootstrap modal not working in React typescript app but working on the fiddleBootstrap modal 不能在 React 打字稿应用程序中工作,但在小提琴上工作
【发布时间】:2019-12-12 02:38:43
【问题描述】:

根据我目前的研究:

这里是调试版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>

相同的代码生成一个可拖动的模式,同时保持背景可用on the fiddle

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

【问题讨论】:

  • 在 dom 准备好之前注册点击处理程序,这使得它变得多余。尝试将点击处理程序移动到 componentDidMount。 cdm("$('#btn1').click(handler fn)))。小提琴可以工作,因为在脚本执行之前 dom 已经初始化(因为你没有在那里使用 react)。希望这有帮助
  • @nithin 是的,正确!这解决了我的问题!
  • 快乐编码????

标签: javascript jquery reactjs twitter-bootstrap typescript


【解决方案1】:

使用 React 表带。

npm i reactstrap

<Modal isOpen={true}><Modal/>

【讨论】:

  • 我希望背景也可以使用,这不能满足我的需要
【解决方案2】:

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

componentDidMount() {    
    //modal logic goes here    
}

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-12-27
    • 2021-07-11
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 2018-11-18
    • 1970-01-01
    • 2021-08-25
    相关资源
    最近更新 更多