React react-bootstrap-如何从外部组件关闭模式窗口

时间:2019-06-06 18:56:29

标签: javascript reactjs modal-dialog react-bootstrap

我正在使用版本:

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;

此功能旨在为长时间运行的活动(例如登录)打开。我想在用户单击登录按钮时将其打开,然后在登录完成后将其关闭。除了使用模态窗口内部的关闭按钮外,我很难找到其他方法来关闭它:

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

这当然只允许用户在需要时将其关闭。我已经在要从外部组件调用的组件中添加了一个open和close方法。

我尝试了很多事情:

添加一个id,使用getElementById查找它,然后触发该方法。

Adding a ref to the opening component as described here.

Doing it programmatically as described here.

I got some ideas from this question on how to call methods in other components.

话虽如此,我仍然无法从模态组件本身外部自动关闭模态窗口。

1 个答案:

答案 0 :(得分:0)

这就是我最终要做的。我无法使用'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();