Reaction Reaction-Bootstrap-如何从外部组件关闭模式窗口 [英] React react-bootstrap - How do I close a modal window from an outside component

查看:0
本文介绍了Reaction Reaction-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>
当然,这只允许用户在需要的时候关闭它。我已在组件中添加了要从外部组件调用的打开和关闭方法。

我尝试了许多方法:

添加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.

尽管如此,我仍然无法从模式组件本身外部自动关闭模式窗口。

推荐答案

这是我最终要做的事情。我无法使‘ref’逻辑工作,所以我最终在构造函数中使用了全局引用:

window.progressModal = this;

我还需要更改关闭代码,因为将showModal状态变量设置为FALSE并不会关闭模式窗口。但是,将showMoal设置为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();

这篇关于Reaction Reaction-Bootstrap-如何从外部组件关闭模式窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆