簡體   English   中英

React react-bootstrap - 如何從外部組件關閉模態 window

[英]React react-bootstrap - How do I close a modal window from an outside component

我正在使用版本:

react@16.8.6
react-bootstrap@1.0.0-beta.8

我有一個簡單的模態組件:

import React, { Component } from 'react'

import { Modal } from "react-bootstrap";
import { ProgressBar } from "react-bootstrap";

class ProgressModal extends Component {
  constructor(...args) {
    super(...args);

    this.state = { showModal: false, titleText: ((this.props.titletext === undefined || this.props.titletext === null || this.props.titletext === "") ? "Working..." : this.props.titletext)};

    this.open = this.open.bind(this);
    this.close = this.close.bind(this);
  }

  open() {
    this.setState({showModal: true});
  }

  close() {
    this.setState({showModal: false});
  }

  render() {
    return (
      <Modal centered backdrop="static" keyboard={false} {...this.props}>
        <Modal.Header>
          <Modal.Title className="font-weight-bold">{this.state.titleText}</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <ProgressBar animated striped now={100} />
        </Modal.Body>
      </Modal>
    );
  }
}

export default ProgressModal;

這旨在為長時間運行的活動(如登錄)打開。 我想在用戶單擊登錄按鈕時打開它,然后在登錄完成后關閉它。 除了使用模態 window 內部的關閉按鈕外,我很難找到關閉它的方法:

<Button className="btn-block" variant="danger" onClick={this.props.onHide}>Close</Button>

這當然只允許用戶在需要時關閉它。 我在我想從外部組件調用的組件中添加了一個打開和關閉方法。

我嘗試了很多事情:

添加一個 id,使用 getElementById 找到它,然后觸發該方法。

如此處所述,將 ref 添加到打開組件。

按照此處所述以編程方式執行此操作。

我從這個問題中得到了一些關於如何在其他組件中調用方法的想法。

盡管如此,我仍然無法從模態組件本身外部自動關閉模態 window。

這就是我最終做的事情。 我無法使'ref'邏輯工作,所以我最終在構造函數中使用了全局引用:

window.progressModal = this;

我還需要更改關閉代碼,因為將showModal狀態變量設置為false並沒有執行任何操作來關閉模式窗口。 將showModal設置為true會打開窗口:

<Modal id={"progress-bar-modal-window"} show={this.state.showModal} centered  backdrop="static" keyboard={false} {...this.props}>

open() {
  this.setState({showModal: true});
}

close() {
  this.props.onHide();
}

現在外部組件可以使用以下命令打開模態窗口:

window.progressModal.open();

他們可以使用以下方法關閉它:

window.progressModal.close();

實際上,我使用useRef而不是使用全局引用我通常使用此解決方案https://stackoverflow.com/a/71464748/1770571實現相同的場景並且它適用於我

暫無
暫無

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

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