【Message.tsx】
import Snackbar from '@material-ui/core/Snackbar'; import Alert from '@material-ui/lab/Alert'; import React from 'react'; export const ShowMessage=(props:any)=>{ const {open,openName,message,onClose,duration,severity} = props; const location=props.location?props.location:{ vertical: 'top', horizontal: 'right' }; const msg = (<div dangerouslySetInnerHTML={{__html:message}} />) return ( <Snackbar open={open} autoHideDuration={duration} anchorOrigin={location} onClose={()=>{onClose(openName)}}> <Alert onClose={()=>{onClose(openName)}} severity={severity}> {msg} </Alert> </Snackbar> ) }
【使用】
import React from 'react'; import {ShowMessage} from "./Message"; type State = { msgOpen:boolean message:string } class Example extends React.Component<{}, State> { constructor(props: {} | Readonly<{}>) { super(props); this.state = { msgOpen:false, message:"", } private setStateVal(key: string, value: any) { let state:any = {}; state[key] = value this.setState(state) } render() { return ( <ShowMessage open={this.state.msgOpen} openName='msgOpen' message="操作成功" onClose={(name:string)=>{this.setStateVal(name,false)}} duration={2000} severity="success" /> )} }