如何从另一个 Class 中定义的按钮打开或关闭一个 Class 中定义的模式

How to open or close a Modal defined in one Class from a Button defined in another Class

我正在用 React 和 react-bootstrap 编写一个简单的网络应用程序。我有两个按钮应该打开两个不同的模式。我想将包含按钮的 Class 与两个模态 Classes 分开,例如

var React = require('react');
var ReactDOM = require('react-dom');

import { Button, Modal, closeButton } from 'react-bootstrap';

var Jumbo = React.createClass ({
  render() {
    return (
      <div className="container">
        <Button onClick={Modal1.open}>Modal1</Button>
        <Button onClick={Modal2.open}>Modal2</Button>
        <Modal1 />
        <Modal2 />
      </div>
    );
  }
});

var Modal1 = React.createClass ({
  getInitialState() {
    return {
      showModal: false
    };
  },

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

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

  render() {
    return (
      <Modal show={this.state.showModal} onHide={this.close}>
        <Modal.Header closeButton>
          <Modal.Title>Modal1</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <p>Modal1</p>
        </Modal.Body>
        <Modal.Footer>
          <Button onClick={this.close}>Close</Button>
        </Modal.Footer>
      </Modal>
    );
  }
});

var Modal2 = React.createClass ({
  getInitialState() {
    return {
      showModal: false
    };
  },

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

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

  render() {
    return (
      <Modal show={this.state.showModal} onHide={this.close}>
        <Modal.Header closeButton>
          <Modal.Title>Modal2</Modal.Title>
        </Modal.Header>
        <Modal.Body>
          <p>Modal2</p>
        </Modal.Body>
        <Modal.Footer>
          <Button onClick={this.close}>Close</Button>
        </Modal.Footer>
      </Modal>
    );
  }
});

ReactDOM.render(<Jumbo />, document.getElementById('modal'));

但是onClick={ModalN.open}不起作用。通常我会将 Button 放在 Modal Class 中(根据 the documented example)并执行 onClick={this.open},但我想将两个 Button 元素放在一起,而不是分开 <div>s。传递对模态框的引用的正确方法是什么?

onClick={modalN.open} 不起作用,您需要在 Jumbo 中包含 ModalN 组件:

var Jumbo = React.createClass ({
  getInitialState() {
    return {
      activeModal: null
    }
  },

  openModal(id){
     this.setState({
        activeModal: id
     })
  }

  render() {
    return (
      <div className="container">
        <Button onClick={this.openModal.bind(this,1)}>Modal1</Button>
        <Button onClick={this.openModal.bind(this,2)}>Modal2</Button>
        {this.state.activeModal === 1 ? <Modal1 /> :null}
        {this.state.activeModal === 2? <Modal2 /> : null}
      </div>
    );
  }
});

您还需要将每个模态框的初始 showModal 更改为 true,否则它们永远不会显示(因为 open() 从未被调用):

var Modal1 = React.createClass ({
  getInitialState() {
    return {
      showModal: true
    }
  },
  ...
});