关闭MUI Snackbar通知并在按键上执行操作

时间:2019-04-10 14:37:07

标签: javascript reactjs material-ui

我们创建了一个使用材料ui Snackbar以及操作按钮和关闭按钮的通知系统。我正在尝试为enter添加一个侦听器事件,以便特定通知的操作将触发并关闭Snackbar。我尝试在装入组件时执行此操作,但是在应用程序加载时装入组件,直到它们的状态设置为open时才显示它们。这导致立即触发与Snackbars关联的所有动作。然后,我尝试使用ref,但没有成功。下面,我将显示调用通知的按钮的代码以及通知组件本身。我正在寻找有关如何关闭活动的Snackbar并使用enter激活其动作而不激活其他已安装通知的建议。

更新:我将密钥从enter更改为spacebar,它可以按需工作。看来问题出在enter键本身。

https://material-ui.com/api/root-ref/#__next

import React from 'react';
import { connect } from 'react-redux';
import { withStyles } from '@material-ui/core/styles';
import IconButton from '@material-ui/core/IconButton';
import DeleteIcon from '@material-ui/icons/Delete';
import Tooltip from '@material-ui/core/Tooltip';
import { NotifierConfirm, enqueueInfo } from '@paragon/notification-tools';
import { deleteDocument } from '../../actions/documents';
import { getSelectedDocument } from '../../selectors/documents';
import { jobIsLocked } from '../../modules/jobLocking'; // eslint-disable-line

const styles = ({
  border: {
    borderRadius: 0,
  },
});

class DeleteDocument extends React.Component {
  state = {
    deleteDocumentOpen: false,
  }

  onDeleteFile = () => {
    if (jobIsLocked()) {
      return;
    }

    this.setState({ deleteDocumentOpen: true });
  }

  closeDeleteDocument = () => {
    this.setState({ deleteDocumentOpen: false });
  };

  onConfirmDelete = () => {
    this.props.onDeleteFile(this.props.selectedDocument.id);
    this.setState({ deleteDocumentOpen: false });
  }

  render() {
    const { classes } = this.props;
    return (
      <div>
        <Tooltip disableFocusListener id="delete-tooltip" title="Delete Document">
          <div>
            <IconButton
              className={`${classes.border} deleteDocumentButton`}
              disabled={(this.props.selectedDocument == null)}
              onClick={this.onDeleteFile}
            >
              <DeleteIcon />
            </IconButton>
          </div>
        </Tooltip>
        <NotifierConfirm
          open={this.state.deleteDocumentOpen}
          onClose={this.closeDeleteDocument}
          onClick={this.onConfirmDelete}
          message="Are you sure you want to DELETE this document?"
          buttonText="Delete"
        />
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  const selectedDocument = getSelectedDocument(state);

  return {
    selectedDocument,
  };
};

function mapDispatchToProps(dispatch) {
  return {
    onDeleteFile: (documentId) => {
      dispatch(deleteDocument(documentId));
    },
    enqueueInfo,
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(withStyles(styles)(DeleteDocument));

import React from 'react';
import { withStyles, WithStyles, StyleRulesCallback } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Snackbar from '@material-ui/core/Snackbar';
import IconButton from '@material-ui/core/IconButton';
import CloseIcon from '@material-ui/icons/Close';
import RootRef from '@material-ui/core/RootRef';

interface NotifierConfirmProps {
  open: boolean;
  onClose: any;
  onClick: () => void;
  message: string;
  messageSecondary?: any;
  buttonText: string;
}

type OwnProps = NotifierConfirmProps & WithStyles<typeof styles>;

const styles: StyleRulesCallback = () => ({
  snackbar: {
    marginTop: 85,
    zIndex: 10000000,
    '& div:first-child': {
      '& div:first-child': {
        width: '100%',
      },
    },
  },
  close: {
    padding: 8,
    marginLeft: 8,
  },
  buttonColor: {
    backgroundColor: '#F3D06E',
  },
  messageDiv: {
    width: '100%',
  }
});

class NotifierConfirmComponent extends React.Component<OwnProps> {
  notifierRef: React.RefObject<{}>;
  constructor(props: OwnProps) {
    super(props);
    // create a ref to store the textInput DOM element
    this.notifierRef = React.createRef();
    this.focusNotifier = this.focusNotifier.bind(this);
  }
  keyPressHandler = (event: any) => {
    if (!this.props.open) return;
    if (event.keyCode === 27) {
      this.props.onClose();
    }
    if (event.keyCode === 13) {
      this.props.onClick();
    }
  }

  focusNotifier() {
    // Explicitly focus the text input using the raw DOM API
    // Note: we're accessing "current" to get the DOM node
    // this.notifierRef.current.focus();  this will not work
  }

  componentDidMount() {
    document.addEventListener('keydown', this.keyPressHandler, false);
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.keyPressHandler, false);
  }

  render() {
    const { classes } = this.props;
    return (
      <React.Fragment>
        <RootRef rootRef={this.notifierRef}>
          <Snackbar
            className={classes.snackbar}
            anchorOrigin={{
              vertical: 'top',
              horizontal: 'center',
            }}
            open={this.props.open}
            onClose={this.props.onClose}
            ContentProps={{
              'aria-describedby': 'message-id',
            }}
            message={
              <div className={classes.messageDiv} id="message-id">
                {this.props.message}<br />
                {this.props.messageSecondary}
              </div>}
            action={[
              <Button
                className={`${classes.buttonColor} confirmActionButton`}
                variant="contained"
                key={this.props.buttonText}
                size="small"
                onClick={this.props.onClick}
              >
                {this.props.buttonText}
              </Button>,
              <IconButton
                key="close"
                aria-label="Close"
                color="inherit"
                className={classes.close}
                onClick={this.props.onClose}
              >
                <CloseIcon />
              </IconButton>,
            ]}
          />
        </RootRef>
      </React.Fragment>
    );
  }
}

export const NotifierConfirm = withStyles(styles)(NotifierConfirmComponent);

1 个答案:

答案 0 :(得分:1)

此问题的答案是将事件监听器更改为keyup而不是  keydown。从这篇文章中推断出这一点。 Why do Enter and Space keys behave differently for buttons?