簡體   English   中英

在函數調用時打開模態

[英]Open modal on function call

我有一個帶有函數示例的 js 文件。 我正在另一個 func bellow 中調用該函數。 我現在需要的是在不單擊按鈕的情況下打開我的模式。 它在單擊按鈕時完美運行,但在我的情況下它不是我所需要的。 任何解決方案如何在不單擊此按鈕的情況下在函數調用時顯示此模式?

function Example() {

  return (
    <>
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
  Launch demo modal
</button>
      <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
              <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div class="modal-body">
              ...
      </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
              <button type="button" class="btn btn-primary">Save changes</button>
            </div>
          </div>
        </div>
      </div>
    </>
  );
}


只需定義一個狀態變量,我們稱之為showModal ,用false初始化它,然后在你的代碼中顯示或隱藏基於showModal模式是truefalse

這樣,當您想“手動”顯示它時,您需要做的就是將showModal切換為true如下所示:

this.setState({showModal: true});

你需要一些反應知識才能理解我的答案:)

$("#exampleModal").modal('show');

嘗試在顯示模態的函數中調用它。 也不要忘記導入 . 在調用此函數之前使用 jquery。 您可以在主頁中導入 jquery,一切都會正常工作

我已經通過使用 React Hooks 解決了這個問題。 感謝您的回復。 快樂黑客:)

 function Example() { const [show, setShow] = useState(true); const handleClose = () => setShow(false); const handleShow = () => setShow(true); return ( <> <Modal show={show} onHide={handleClose}> <Modal.Header closeButton> <Modal.Title>Modal heading</Modal.Title> </Modal.Header> <Modal.Body>Woohoo, you're reading this text in a modal!</Modal.Body> <Modal.Footer> <Button variant="secondary" onClick={handleClose}> Close </Button> <Button variant="primary" onClick={handleClose}> Save Changes </Button> </Modal.Footer> </Modal> </> ); }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM