notify.js 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import React, { Component } from 'react';
  2. import style from './index.less';
  3. import className from 'classnames'
  4. import close from "./img/close.png";
  5. class NotifyBox extends Component {
  6. constructor() {
  7. super()
  8. this.transitionTime = 300
  9. this.state = { notices: [] ,timer:null}
  10. this.removeNotice = this.removeNotice.bind(this)
  11. }
  12. getNoticeKey() {
  13. const { notices } = this.state
  14. return `notice-${new Date().getTime()}-${notices.length}`
  15. }
  16. addNotice(notice) {
  17. const { notices } = this.state
  18. notice.key = this.getNoticeKey()
  19. // notices.push(notice);//展示所有的提示
  20. notices[0] = notice;//仅展示最后一个提示
  21. this.setState({ notices })
  22. if (notice.duration > 0) {
  23. clearTimeout(this.state.timer);
  24. const timer = setTimeout(() => {
  25. this.removeNotice(notice.key)
  26. }, notice.duration)
  27. this.setState({timer})
  28. }
  29. return () => { this.removeNotice(notice.key) }
  30. }
  31. removeNotice(key) {
  32. const { notices } = this.state
  33. this.setState({
  34. notices: notices.filter((notice) => {
  35. if (notice.key === key) {
  36. if (notice.onClose) setTimeout(notice.onClose, this.transitionTime)
  37. return false
  38. }
  39. return true
  40. })
  41. })
  42. }
  43. render() {
  44. const { notices } = this.state
  45. const icons = {
  46. info: 'notify-info',
  47. success: 'notify-success',
  48. error: 'notify-error',
  49. }
  50. const styles = {
  51. success: {background:'#000',color:'#fff',opacity:'0.8'},
  52. error: {background:'#000',color:'#fff',opacity:'0.8'},
  53. info:{background:'#000',color:'#fff',opacity:'0.8'}
  54. // success: {background:'#7F7F7F',color:'#fff'},
  55. // error: {background:'#7F7F7F',color:'#fff'},
  56. // info:{background:'#7F7F7F',color:'#fff'}
  57. }
  58. return (
  59. <div className={style["notify"]}>
  60. {
  61. notices.map(notice => (
  62. <div className={style["notify-bg"]} key={notice.key}>
  63. <div className={style['notify-box']} style={styles[notice.type]}>
  64. <div className={style[`${icons[notice.type]}`]}></div>
  65. <div className={style['notify-text']}>{notice.content}</div>
  66. {notice.showClose&&<img className={style['notify-close']} onClick={()=>{this.removeNotice(notice.key)}} src={close}/>}
  67. </div>
  68. </div>
  69. ))
  70. }
  71. </div>
  72. )
  73. }
  74. }
  75. export default NotifyBox