React:关闭来自Parent的Child Component中的Modal

时间:2017-12-05 08:43:22

标签: javascript reactjs react-bootstrap

我在子组件中有一个模态,用于处理父组件中的删除功能。孩子持有模态的状态(开放或封闭),因为这似乎是最合乎逻辑的地方。

 removeItem() {
   console.log('clicked');
  };

 ...

 <DeleteButton deleterecord={()=>this.removeItem(data.row._original._id)}/>

儿童

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

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


render() {

 return(
  <div>
    <Button
    bsStyle="primary"
    bsSize="small"
    onClick={this.open.bind(this)}
  >
    Delete
  </Button>

  <Modal
    show={this.state.showModal}
    onHide={this.close.bind(this)}
    bsSize="small"
    >
   ...

在removeItem代码运行后,如何从父级关闭模式。

1 个答案:

答案 0 :(得分:3)

您可以使用ref来调用子关闭函数吗?

<强>父

    removeItem() {
       console.log('clicked');
       this.child.close();
    }

   render() {
      return (
         <div>
            <ChildWithModal ref={(ref) => { this.child = ref; }} />
         </div>
      );
   }

儿童

...

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