reactjs - 如何让 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
,但是在再次提交表单之前如何“重置”此状态?
解决方案
一种方法是你可以稍微改变你的方法并且总是Alert
渲染,即
<Alert message={this.state.error} open={this.state.open} onClose={()=>{this.setState({open:false})}}/>
还将open
状态变量从Alert
的状态移动到其父级。所以在Alert
使用open
道具的价值时总是如此。现在,无论何时open
更改父级,Alert
都会重新正确渲染。
推荐阅读
- node.js - jwt令牌过期后如何注销
- gradle - 当我尝试运行我的颤振应用程序时,它在运行 gradle 时出现错误
- apache-kafka - 如何在 Quarkus-Kafka 消费者方法中执行 JPA 实体管理器操作
- javascript - 这是JS错误吗?
- python - Kubernetes 上的生产就绪 Python 应用程序
- python-3.x - pywinauto 没有使用 .print_control_identifiers() 看到 ListView 对象
- php - 无法访问所有会话数据
- ruby-on-rails - 如何在作用域上使用“或”
- python - 计算 pandas 数据框行中列表的平均值和标准偏差
- reactjs - 在编译我的反应应用程序时,我得到 Module build failed: SyntaxError: Unexpected token