动态菜单和动态路由的 antd pro

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. import React, { Component } from 'react';
  2. function fixedZero(val) {
  3. return val * 1 < 10 ? `0${val}` : val;
  4. }
  5. class CountDown extends Component {
  6. constructor(props) {
  7. super(props);
  8. const { lastTime } = this.initTime(props);
  9. this.state = {
  10. lastTime,
  11. };
  12. }
  13. componentDidMount() {
  14. this.tick();
  15. }
  16. componentWillReceiveProps(nextProps) {
  17. if (this.props.target !== nextProps.target) {
  18. clearTimeout(this.timer);
  19. const { lastTime } = this.initTime(nextProps);
  20. this.setState(
  21. {
  22. lastTime,
  23. },
  24. () => {
  25. this.tick();
  26. }
  27. );
  28. }
  29. }
  30. componentWillUnmount() {
  31. clearTimeout(this.timer);
  32. }
  33. timer = 0;
  34. interval = 1000;
  35. initTime = props => {
  36. let lastTime = 0;
  37. let targetTime = 0;
  38. try {
  39. if (Object.prototype.toString.call(props.target) === '[object Date]') {
  40. targetTime = props.target.getTime();
  41. } else {
  42. targetTime = new Date(props.target).getTime();
  43. }
  44. } catch (e) {
  45. throw new Error('invalid target prop', e);
  46. }
  47. lastTime = targetTime - new Date().getTime();
  48. return {
  49. lastTime: lastTime < 0 ? 0 : lastTime,
  50. };
  51. };
  52. // defaultFormat = time => (
  53. // <span>{moment(time).format('hh:mm:ss')}</span>
  54. // );
  55. defaultFormat = time => {
  56. const hours = 60 * 60 * 1000;
  57. const minutes = 60 * 1000;
  58. const h = Math.floor(time / hours);
  59. const m = Math.floor((time - h * hours) / minutes);
  60. const s = Math.floor((time - h * hours - m * minutes) / 1000);
  61. return (
  62. <span>
  63. {fixedZero(h)}:{fixedZero(m)}:{fixedZero(s)}
  64. </span>
  65. );
  66. };
  67. tick = () => {
  68. const { onEnd } = this.props;
  69. let { lastTime } = this.state;
  70. this.timer = setTimeout(() => {
  71. if (lastTime < this.interval) {
  72. clearTimeout(this.timer);
  73. this.setState(
  74. {
  75. lastTime: 0,
  76. },
  77. () => {
  78. if (onEnd) {
  79. onEnd();
  80. }
  81. }
  82. );
  83. } else {
  84. lastTime -= this.interval;
  85. this.setState(
  86. {
  87. lastTime,
  88. },
  89. () => {
  90. this.tick();
  91. }
  92. );
  93. }
  94. }, this.interval);
  95. };
  96. render() {
  97. const { format = this.defaultFormat, onEnd, ...rest } = this.props;
  98. const { lastTime } = this.state;
  99. const result = format(lastTime);
  100. return <span {...rest}>{result}</span>;
  101. }
  102. }
  103. export default CountDown;