Home Reference Source Repository

src/components/indicator/Indicator.js

  1. /**
  2. * @author haw
  3. */
  4.  
  5. import React, {
  6. PropTypes,
  7. Component
  8. } from 'react';
  9. import {
  10. IconLoading
  11. } from '../icon';
  12. import Portal from '../portal';
  13. import {classNames} from '../util';
  14.  
  15. const prefix = 'indicator';
  16.  
  17. /**
  18. * 活动指示器
  19. */
  20. export default class Indicator extends Component {
  21.  
  22. /**
  23. * 构造函数
  24. * @param {Object} props 组件所使用的属性
  25. * @param {PropTypes.node} [props.icon] 指示器要显示的图标
  26. * @param {PropTypes.node} [props.content] 指示器要显示的内容
  27. * @param {boolean} [props.visible] 活动指示器是否显示
  28. * @param {number} [props.timeout] 活动指示器自动关闭的时间
  29. * @param {function} props.close 关闭指示器的回调(配合 API 调用来使用,一般不用手动传)
  30. * @param {Object} context
  31. */
  32. constructor(props, context) {
  33. super(props, context);
  34.  
  35. this.timer = null;
  36. }
  37.  
  38. componentDidMount() {
  39. this._delayClose();
  40. }
  41.  
  42. componentDidUpdate() {
  43. this._delayClose();
  44. }
  45.  
  46. _delayClose() {
  47. const {
  48. visible,
  49. timeout,
  50. close,
  51. onClose
  52. } = this.props;
  53.  
  54. if (visible && timeout) {
  55. clearTimeout(this.timer);
  56. this.timer = setTimeout(() => {
  57. onClose && onClose();
  58. close && close();
  59. }, timeout);
  60. }
  61. }
  62.  
  63. render() {
  64. const {
  65. icon,
  66. content,
  67. visible,
  68. timeout,
  69. close,
  70. onClose,
  71. className,
  72. children,
  73. ...rest
  74. } = this.props;
  75. let clazz = classNames(prefix, {
  76. [className]: className
  77. });
  78.  
  79. if (!visible) {
  80. return null;
  81. }
  82. return (
  83. <div className={clazz} {...rest}>
  84. {icon ? (
  85. <div><IconLoading /></div>
  86. ) : null}
  87. <p>{content || children}</p>
  88. </div>
  89. );
  90. }
  91. }
  92.  
  93. Indicator.propTypes = {
  94. icon: PropTypes.node,
  95. content: PropTypes.node,
  96. visible: PropTypes.bool,
  97. timeout: PropTypes.number,
  98. close: PropTypes.func,
  99. onClose: PropTypes.func,
  100. className: PropTypes.string,
  101. children: PropTypes.node
  102. };
  103.  
  104. /**
  105. * 活动指示器组件的 API 调用方法
  106. * @param {Object} props @see Indicator 组件属性
  107. * @param {Node} container 活动指示器的容器节点
  108. */
  109. Indicator.show = (props, container) => {
  110. props.timeout = props.timeout || 1500;
  111. Portal.show(Indicator, props, container);
  112. };