簡體   English   中英

React-設置父組件的狀態以關閉子組件的模態

[英]React - set state of parent component to close modal from a child component

我在父級中設置模態組件的狀態以處理打開和關閉它的過程。 初始顯示狀態為false,在單擊事件中,顯示狀態為true,並出現模式彈出窗口。 這工作正常,問題是我無法將其關閉。 我似乎無法從子級中調用父級組件中的handleHide函數。

class Parent extends Component {
    constructor(props) {
      super(props);
      this.handleHide = this.handleHide.bind(this);
      this.state = {
        show: false
      };
    }
    handleHide() {
      this.setState({ show: false });
    }
    renderRow() {
      return (
        <tr>
          <td onClick={() => this.setState({ show: true })}>test</td>
          <ChildModal show={this.state.show} handleHide={this.handleHide}/>
        </tr>
      );
    }
}


class ChildModal extends Component {
  render() {
    return (
       <Modal onHide={() => this.props.handleHide()} show={this.props.show}>
            <Modal.Header closeButton> 
            <Modal.Title>Test</Modal.Title> 
            </Modal.Header>
            <Modal.Body> 
                {/* some text */}
            </Modal.Body>
        </Modal>
    );
  }
}

您的問題是您要將onHide傳遞為Modal組件的道具。 Modal ,您需要定義onHide含義

如果您使用reactstrap,請使用以下模態:首先從reactstrap導入所有內容

<Modal isOpen={this.state.modal} toggle={this.toggle} className={this.props.className}>
      <ModalHeader toggle={this.toggle}>Modal 

title</ModalHeader>
          <ModalBody>
                Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt.
              </ModalBody>
              <ModalFooter>
                <Button color="primary" onClick={this.toggle}>Do Something</Button>{' '}
                <Button color="secondary" onClick={this.toggle}>Cancel</Button>
              </ModalFooter>
            </Modal>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM