Toast组件的简化版,模仿antd的消息组件封装。组件文件(.jsx)Toast/index.jsx/\*\*\*@nameToast\*@authordarcrand\*@date2020-01-20\*@descTipsinfo\*/importReact,{Component}from'react'importReactDOMfrom'react-dom'import{CSSTransition,TransitionGroup}from'react-transition-group'import'./styles.less'importicoInfofrom'@/assets/component-toast/toast-info.svg'importicoSuccessfrom'@/assets/component-toast/toast-success.svg'importicoWarningfrom'@/assets/component-toast/toast-warning.svg'importicoErrorfrom'@/assets/component-toast/toast-error.svg'//切换动画时长(ms),需要和'less'中的'@time'保持一致constANIMATION\_DURATION\_TIME\=250//api(提示符)typeconstTOAST\_TYPES\=\['info','success','warning','error'\]//持续时间(ms)constDEFAULT\_DURATION\=3000classToastextendsComponent{state\={zIndex:100,//防止被覆盖top:0,//距离top位置的距离(px)defaultDuration:DEFAULT\_DURATION,//提示时长(ms)list:\[\],//提示内容列表}setConfig\=(config\={})\=>{const{zIndex\=100,top\=0,defaultDuration\=DEFAULT\_DURATION}\=configthis.setState({zIndex,top,defaultDuration})}/\*\*\*@description添加提示\*\*@param{Object}options选项\*@param{String}options.type类型enum:TOAST\_TYPES\*@param{String}options.content内容\*@param{Number}options.duration持续时间\*/add\=(options\={})\=>{const{list,defaultDuration}\=this.stateconstid\=Date.now()constitem\={id,...options}this.setState({list:list.concat(item)},()\=>{consttimer\=setTimeout(()\=>{clearTimeout(timer)this.setState(prev\=>({list:prev.list.filter(v\=>v.id!==id)}))},options.duration||defaultDuration)})}render(){const{zIndex,top,list}\=this.stateif(!Array.isArray(list)){returnfalse}return(
