Я создал компонент 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
, но как я могу "сбросить" этосостояние до повторной отправки формы?