首页 > 解决方案 > 如何让 Snackbar 再次打开?

问题描述

我创建了一个Snackbar组件。

import React, { Component } from 'react';
import { Snackbar, IconButton } from '@material-ui/core';
import CloseIcon from '@material-ui/icons/Close';

interface AlertProps {
  message: string;
}

interface AlertState {
  open: boolean;
}

export default class Alert extends Component<AlertProps, AlertState> {
  constructor(props: AlertProps) {
    super(props);
    this.state = {
      open: true
    };
    this.handleClose = this.handleClose.bind(this);
  }
  handleClose(event: React.SyntheticEvent | React.MouseEvent, reason?: string) {
    if (reason !== 'clickaway') {
      this.setState({
        open: false
      });
    }
  }
  render() {
    return (
      <Snackbar
        anchorOrigin={{
          vertical: 'bottom',
          horizontal: 'left',
        }}
        open={this.state.open}
        autoHideDuration={6000}
        onClose={this.handleClose}
        message={this.props.message}
        action={
          <IconButton
            key="close"
            color="inherit"
            onClick={this.handleClose}
          >
            <CloseIcon />
          </IconButton>
        }
      />
    )
  }
}

然后,当提交表单时遇到错误时,我以编程方式将其添加到渲染中。

let alert: ReactNode;
if (this.state.error) {
  alert = <Alert message={this.state.error} />;
}

问题是Snackbar第一次遇到错误时才打开。如果用户两次提交相同的表单,Snackbar则不会打开。

我知道这是由于方法this.state.open = false设置的原因onClose,但是在再次提交表单之前如何“重置”此状态?

标签: reactjsmaterial-ui

解决方案


一种方法是你可以稍微改变你的方法并且总是Alert渲染,即

<Alert message={this.state.error} open={this.state.open} onClose={()=>{this.setState({open:false})}}/>

还将open状态变量从Alert的状态移动到其父级。所以在Alert使用open道具的价值时总是如此。现在,无论何时open更改父级,Alert都会重新正确渲染。


推荐阅读