【问题标题】:Any on hide event for react-toolbox snackbar?react-toolbox 小吃店的任何隐藏事件?
【发布时间】:2017-03-31 03:25:46
【问题描述】:

我正在使用带有 Redux 的 react-toolkit Snackbar 组件。每个snackbar 都被建模为Redux store 中的一个对象。但我想在每次通知超时或被解除/隐藏时删除此对象。我如何实现这一目标?

每次添加通知时是否需要手动将onTimeout 设置为dispatch 事件?

如果是这样,有没有办法在中心位置添加这个调度,而不是在我调度这个动作的任何地方添加它?

【问题讨论】:

    标签: reactjs redux react-toolbox


    【解决方案1】:

    也许你可以在这里使用更高阶的组件。

    SnackbarWrapper.js

    import React from 'react';
    import PropTypes from 'prop-types';
    
    const SnackbarWrapper = (Component) => {
      class Decorated extends React.Component {
        constructor(props, context) {
          super(props, context);
          this.state = {
            active: props.active
          };
          this.handleSnackbarClick = this.handleSnackbarClick.bind(this);
          this.handleSnackbarTimeout = this.handleSnackbarTimeout.bind(this);
        }
        componentWillReceiveProps(nextProps) {
          // snackbar activated from outside
          if (this.props.active !== nextProps.active) {
            this.setState({ active: true });
          }
        }
        handleSnackbarClick(event, instance) {
          // snackbar dismissed from inside
          this.setState({ active: false });
          // handle the dispatch in callback function
          this.props.cb();
        }
        handleSnackbarTimeout(event, instance) {
          // snackbar dismissed from inside
          this.setState({ active: false });
          // handle the dispatch in callback function
          this.props.cb();
        }
        render() {
          const { action, label, type, timeout } = this.props;
          return (
            <Component
              action={action}
              label={label}
              type={type}
              timeout={timeout}
              active={this.state.active}
              onClick={this.handleSnackbarClick}
              onTimeout={this.handleSnackbarTimeout}
            />
          );
        }
      }
    
      Decorated.propTypes = {
        action: PropTypes.string.isRequired,
        label: PropTypes.string.isRequired,
        type: PropTypes.string.isRequired,
        timeout: PropTypes.number.isRequired,
        cb: PropTypes.func.isRequired,
        active: PropTypes.bool.isRequired
      };
    
      return Decorated;
    };
    
    export default SnackbarWrapper;
    

    在你的组件中

    import SnackbarWrapper from './SnackBarWrapper';
    const RTSnackbar = SnackbarWrapper(Snackbar);
    ...
    <RTSnackbar
      action="Dismiss"
      label="Snackbar action cancel"
      type="cancel"
      timeout={2000}
      cb={this.actionCb}
      active={this.state.active}
     />
    

    【讨论】:

      猜你喜欢
      • 2016-06-28
      • 1970-01-01
      • 2019-12-10
      • 2020-07-25
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 2020-07-05
      • 2018-09-13
      相关资源
      最近更新 更多