使用ReactStrap的模态组件

时间:2019-02-27 16:34:05

标签: reactjs reactstrap

目前,我有一个组件(Logbook.js),其中有一个日志表,每个日志都有一个唯一的键。当我单击表格行时,模式会以模式显示该行的数据。从此模式中,当我单击“更新”时,将出现另一个模式,并且数据以整齐的形式显示,可随时更新。我想将这些模式分为独立的组件DisplayModal.js和UpdateModal.js。我该怎么做才能使行中包含的数据被传送到组件?

1 个答案:

答案 0 :(得分:0)

这可以让您知道从哪里开始:

const { Button, Modal, ModalHeader, ModalBody, ModalFooter } = Reactstrap;

class Modal1 extends React.Component {
  render() {
    return (
        <React.Fragment>
          <ModalHeader toggle={this.toggle}>{this.props.title}</ModalHeader>
          {this.props.children}
        </React.Fragment>
    )
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      modal: false,
      modalType: 1
    };

    this.toggle = this.toggle.bind(this);
    this.changeModalType = this.changeModalType.bind(this);
  }

  changeModalType(type) {
    this.setState({modalType: type});
  }
  
  toggle() {
    this.setState(prevState => ({
      modal: !prevState.modal
    }));
  }
  
  renderDisplayModal() {
  return(
  <React.Fragment>
          <ModalBody>
              This is display modal
          </ModalBody>
          <ModalFooter>
            <Button color="primary" onClick={() => this.changeModalType(2)}>Open Update Modal</Button>{' '}
            <Button color="secondary" onClick={this.toggle}>Cancel</Button>
          </ModalFooter>
          </React.Fragment>
  );
  }
  
  renderUpdateModal() {
    return(
  <React.Fragment>
          <ModalBody>
              This is update modal
          </ModalBody>
          <ModalFooter>
            <Button color="primary" onClick={() => this.changeModalType(1)}>Open Display Modal</Button>{' '}
            <Button color="secondary" onClick={this.toggle}>Cancel</Button>
          </ModalFooter>
          </React.Fragment>
    );
  }

  render() {
    return (
      <div>
        <Button color="danger" onClick={this.toggle}>Open</Button>
        <Modal isOpen={this.state.modal} toggle={this.toggle}>
          <Modal1 click={this.toggle} title={this.state.modalType === 1 ? 'Display title' : 'Update Modal'}>
            {this.state.modalType === 1
              ? this.renderDisplayModal()
              : this.renderUpdateModal()
            }
          </Modal1>
        </Modal>
      </div>
    );
  } 
}

ReactDOM.render( < App / > ,
  document.getElementById('root')
);
<script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/reactstrap/6.0.1/reactstrap.full.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css" crossorigin="anonymous">
<div id="root" />