Я использую Snack bar со страницы Материал-пользовательский интерфейс (первый пример — Customized SnackBars)
const variantIcon = {
success: CheckCircleIcon,
warning: WarningIcon,
error: ErrorIcon,
info: InfoIcon,
};
const styles1 = theme => ({
success: {
backgroundColor: green[600],
},
error: {
backgroundColor: theme.palette.error.dark,
},
info: {
backgroundColor: theme.palette.primary.dark,
},
warning: {
backgroundColor: amber[700],
},
icon: {
fontSize: 20,
},
iconVariant: {
opacity: 0.9,
marginRight: theme.spacing.unit,
},
message: {
display: 'flex',
alignItems: 'center',
},
});
function MySnackbarContent(props) {
const { classes, className, message, onClose, variant, ...other } = props;
const Icon = variantIcon[variant];
return (
<SnackbarContent
className = {classNames(classes[variant], className)}
aria-describedby = "client-snackbar"
message = {
<span id = "client-snackbar" className = {classes.message}>
<Icon className = {classNames(classes.icon, classes.iconVariant)} />
{message}
</span>
}
action = {[
<IconButton
key = "close"
aria-label = "Close"
color = "inherit"
className = {classes.close}
onClick = {onClose}
>
<CloseIcon className = {classes.icon} />
</IconButton>,
]}
{...other}
/>
);
}
MySnackbarContent.propTypes = {
classes: PropTypes.object.isRequired,
className: PropTypes.string,
message: PropTypes.node,
onClose: PropTypes.func,
variant: PropTypes.oneOf(['success', 'warning', 'error', 'info']).isRequired,
};
const MySnackbarContentWrapper = withStyles(styles1)(MySnackbarContent);
const styles2 = theme => ({
margin: {
margin: theme.spacing.unit,
},
});
class CustomizedSnackbar extends React.Component {
state = {
open: false,
};
handleClick = () => {
this.setState({ open: true });
};
handleClose = (event, reason) => {
if (reason === 'clickaway') {
return;
}
this.setState({ open: false });
};
render() {
return (
<div>
<Snackbar
anchorOrigin = {{
vertical: 'bottom',
horizontal: 'left',
}}
open = {this.state.open}
autoHideDuration = {2000}
onClose = {this.handleClose}
>
<MySnackbarContentWrapper
onClose = {this.handleClose}
variant = "error"
message = "This is an error message!"
/>
</Snackbar>
</div>
);
}
}
export default withStyles(styles2)(CustomizedSnackbar);
В примере закусочная отображается при нажатии на кнопку "ОТКРЫТЬ УСПЕХ ЗАКУСОЧНУЮ"
Я хотел бы показать закусочную с ошибкой, когда Мутация от Аполлона в моей форме дает ошибку.
render(){
return(
<div>
<Mutation
mutation = {this.mutationQuery}
onError = {() =>
//here show Snack Bar
}
onCompleted = {data => { console.info(data); }}
>
{mutation => (
//here is the form
)}
)}
Проблема в том, что я не знаю, как вызвать отображение SnackBar в функции при ошибке. Как изменить состояние Snack Bar? Я пробовал решение от здесь, но получаю сообщение об ошибке
openSnackbarFn is not a function
Заранее спасибо.
создайте функцию, а затем вызовите ее как из onError, так и из onComplete
но как должна выглядеть эта функция?
нормальная функция javascript и вызывайте ее так же, как вы вызываете функции для прослушивателей событий из ваших реагирующих компонентов
но как эта функция скажет Snackbar показать, как она может изменить состояние в Snackbar?
пример пожалуйста..
Давайте продолжить обсуждение в чате.





По сути, вы хотите, чтобы ваш Snackbar был братом вашей Mutation, и пусть их общий родитель (т.е. ваш компонент) обрабатывает открытое/закрытое состояние Snackbar.
Компонент в стиле класса
class FormWithMutationAndSnackbar extends React.Component {
state = {
open: false
}
handleOpen = () => this.setState({ open: true })
handleClose = () => this.setState({ open: false })
render() {
const { open } = this.state
return(
<React.Fragment>
<Mutation
mutation = {this.mutationQuery}
onError = {(err) => {
// use err to set Snackbar contents for example
this.handleOpen()
}
onCompleted = {data => { console.info(data); }}
>
{mutation => (
//here is the form
)}
</Mutation>
<Snackbar
open = {open}
onClose = {this.handleClose}
// other Snackbar props
>
// Snackbar contents
</Snackbar>
</React.Fragment>
)
}
}
Функциональный компонент с хуками
const FormWithMutationAndSnackbar = () => {
const [open, setOpen] = useState(false)
return(
<React.Fragment>
<Mutation
mutation = {this.mutationQuery}
onError = {(err) => {
// use err to set Snackbar contents for example
setOpen(true)
}
onCompleted = {data => { console.info(data); }}
>
{mutation => (
//here is the form
)}
</Mutation>
<Snackbar
open = {open}
onClose = {() => setOpen(false)}
// other Snackbar props
>
// Snackbar contents
</Snackbar>
</React.Fragment>
)
}
также, но я хочу показать сообщение о появлении ошибки