【问题标题】:React - set state of parent component to close modal from a child componentReact - 将父组件的状态设置为从子组件关闭模式
【发布时间】:2018-09-14 13:24:29
【问题描述】:

我在父级中设置了模态组件的状态以处理打开和关闭它。初始显示状态为假,在单击事件时显示状态变为真并出现模式弹出窗口。这工作正常,问题是我无法关闭它。我似乎无法从子组件调用父组件中的 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>
    );
  }
}

【问题讨论】:

  • 得到了解决方案......我也遇到了类似的问题......请在这里更新......提前谢谢

标签: reactjs


【解决方案1】:

您的问题是您将onHide 作为道具传递给Modal 组件。在Modal 中,您需要定义onHide 的含义

【讨论】:

    【解决方案2】:

    如果您使用 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>
    

    【讨论】:

      猜你喜欢
      • 2020-12-14
      • 2021-03-14
      • 2020-10-06
      • 2018-05-18
      • 2018-07-20
      • 2022-07-15
      • 2018-01-02
      • 2021-03-21
      • 1970-01-01
      相关资源
      最近更新 更多