【问题标题】:React react-bootstrap - How do I close a modal window from an outside componentReact react-bootstrap - 如何从外部组件关闭模式窗口
【发布时间】:2019-06-06 18:56:29
【问题描述】:

我正在使用版本:

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.

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

【问题讨论】:

    标签: javascript reactjs modal-dialog react-bootstrap


    【解决方案1】:

    这就是我最终要做的事情。我无法让“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();
    

    【讨论】:

      【解决方案2】:

      其实我用useRef而不是使用全局引用 我通常使用此解决方案 https://stackoverflow.com/a/71464748/1770571 实现相同的场景,它适用于我

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-30
        • 2012-04-11
        • 2017-11-25
        • 1970-01-01
        • 2020-07-30
        相关资源
        最近更新 更多