import React , { useState } from 'react' ; import ReactDOM from 'react-dom' ; import { Snackbar } from '@material-ui/core' ; import { SnackbarProps } from '@material-ui/core/Snackbar' ; import MySnackbarContent from './MySnackbarContent' ; type ISnackBar = Pick < SnackbarProps , 'autoHideDuration' | 'anchorOrigin' > & { message : string ; variant ? : 'info' | 'success' | 'error' ; } ; /**
 * 指向 MySnackBar 的引用
 */ let snackBarRef ! ; const MySnackBar = ( ) => { const [ open , setOpen ] = useState ( false ) ; const handleClose = ( ) => setOpen ( false ) ; const [ snackBarProps , setSnackBarProps ] = useState < ISnackBar > ( { message : 'NO MSG' , } ) ; const pushSnackBar = ( props ) => { setSnackBarProps ( props ) ; setOpen ( true ) ; } ; snackBarRef = pushSnackBar ; return ( < Snackbar open = { open } onClose = { handleClose } anchorOrigin = { { vertical : 'top' , horizontal : 'center' , } } autoHideDuration = { snackBarProps . autoHideDuration || 4000 } message = { snackBarProps . message } > < MySnackbarContent variant = { snackBarProps . variant || 'info' } message = { snackBarProps . message } onClose = { handleClose } / > < /Snackbar>); } ; function snackbar ( snackBarProps ) { snackBarRef ( snackBarProps ) ; } snackbar . info = ( message ) => { snackbar ( { variant : 'info' , message , } ) ; } ; snackbar . success = ( message ) => { snackbar ( { variant : 'success' , message , } ) ; } ; snackbar . error = ( message ) => { snackbar ( { variant : 'error' , message , } ) ; } ; export default snackbar ; const snackbarDom = document . createElement ( 'div' ) ; document . body . append ( snackbarDom ) ; function renderSnackBar ( ) { ReactDOM . render ( < MySnackBar />, snackbarDom); } renderSnackBar ( ) ;