反应/材料 UI - 处理子组件中的打开/关闭框



所以在我的父类中,我目前有以下代码片段:

...
return (
      <div className={prefix}>
      {(toEditBooking===true ? <EditBooking editBooking={true} booking={selected}/> : null)}
      <Paper style={header} rounded={false}>
        <div className ={prefix+'-name'}>{name}</div>
        <div className ={prefix+'-flight'}>{refNo}</div>
        <div className ={prefix+'-initials'}>{initials}</div>
        <div className ...

正如你所注意到的,我有一个"toEditBooking===true",如果满足条件,它会加载一个名为EditBooking的组件并传递一系列道具。

在名为EditBooking的子组件中,我有以下内容:

componentWillReceiveProps = () => {
  this.setState({open:this.props.editBooking})
}
state = {
  open: this.props.editBooking,
};
handleClose = () => {
  this.setState({open: false});
};
  render () {
    const actions = [
      <FlatButton
        label="Cancel"
        primary={true}
        onClick={this.handleClose}
      />,
      <FlatButton
        label="Submit"
        primary={true}
        keyboardFocused={true}
        onClick={this.handleClose}
      />,
    ];
    const booking = this.props.booking
    console.log(booking)
    return (
        <Dialog
          title="Edit Booking"
          autoDetectWindowHeight={false}
          autoScrollBodyContent={false}
          actions={actions}
          modal={false}
          open={this.state.open}
          onRequestClose={this.handleClose}
        >
        <Paper className={prefix}>
        <Subheader>Please update the correct details below:</Subheader>
         <Subheader>Flight Details</Subheader>
         <Row middle="xs">

这第一次效果很好,但是,如果用户关闭子组件(EditBooking),我希望父组件更新其道具。

有没有容易实现的?

将另一个 prop 传递给您的子组件 onClose 中,这将是子组件在关闭时将调用的回调。

<EditBooking editBooking={true} booking={selected} onClose={() => {
  // put all your logic to handle closing in the parent component
  // e.g. this.setState({ editBooking: false });
}} />

然后修改 EditBooking.handleClose

handleClose = () => {
  this.setState({open: false});
  this.props.onClose(); // call callback provided by parent
};

最新更新