1

如果用户按下按钮两次,我会打开一个模式窗口。但我想在另一个组件中使用它,所以我想让它可重用。来自 Redux 的模态使用状态('randomActivity' 是数据,'repeatedActivity' 是布尔值)。所以,我对代码重构感到困惑。

这是初始代码

class RepeatedModal extends Component {
  closeRepeatedToast = () => {
    this.props.closeRepeatedToast(false);
  };

  render() {
    const { repeatedActivity, randomActivity, classes } = this.props;

    return (
      <div>
        <Modal
          aria-labelledby="transition-modal-title"
          aria-describedby="transition-modal-description"
          className={classes.modal}
          open={repeatedActivity}
          onClose={this.closeRepeatedToast}
          closeAfterTransition
          BackdropComponent={Backdrop}
          BackdropProps={{
            timeout: 500,
          }}
        >
          <Fade in={repeatedActivity}>
            <div className={classes.modalPaper}>
              <h2 id="transition-modal-title">
                "{randomActivity.activity}" was already saved
              </h2>
            </div>
          </Fade>
        </Modal>
      </div>
    );
  }
}

export default ModalComponent(
  withStyles(styles, { withTheme: true })(RepeatedModal)
);

这是重构后的代码。

const RepeatedModal = ({data}) => ((
  <div>
          <Modal
             aria-labelledby="transition-modal-title"
            aria-describedby="transition-modal-description"
             className={classes.modal}
             open={repeatedActivity}
             onClose={this.closeRepeatedToast}
             closeAfterTransition
             BackdropComponent={Backdrop}
             BackdropProps={{
               timeout: 500,
             }}
           >
             <Fade in={repeatedActivity}>
               <div className={classes.modalPaper}>
                 <h2 id="transition-modal-title">
                   "{randomActivity.activity}" was already saved
                 </h2>
               </div>
             </Fade>
           </Modal>
         </div>
))
export default ModalComponent(
  withStyles(styles, { withTheme: true })(RepeatedModal)
);

和临时的

const ModalComponent = (WrappedComponent) => {
  return class extends Component {
    closeRepeatedToast = () => {
      this.props.closeRepeatedToast(this.data);
    };

    render() {
      

      return <WrappedComponent {...this.props} data={this.state.data} />;
    }
  };
};

export default ModalComponent;
4

0 回答 0