Guest User

Untitled

a guest
Apr 24th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. class CountDown extends React.Component {
  2. constructor({count = 10}) {
  3. super();
  4. this.count = count;
  5. this.state = {
  6. isCounting: false,
  7. count: this.count
  8. };
  9. this.onClickHandler = this.onClickHandler.bind(this);
  10. }
  11.  
  12. onClickHandler() {
  13. if (this.state.isCounting) {
  14. return false;
  15. }
  16. this.startCounting();
  17. }
  18.  
  19. startCounting() {
  20. this.setState({
  21. ...this.state,
  22. isCounting: true
  23. }, () => {
  24. setTimeout(() => this.countDown(), 1000);
  25. });
  26. }
  27.  
  28.  
  29. componentDidMount() {
  30. if (this.props.auto) {
  31. this.startCounting();
  32. }
  33. }
  34.  
  35. clearTimer() {
  36. this.timer && clearTimeout(this.timer);
  37. }
  38.  
  39. componentWillUnmount() {
  40. this.clearTimer();
  41. }
  42.  
  43. countDown() {
  44. var currentCount = this.state.count;
  45. if (currentCount) {
  46. this.setState({
  47. ...this.state,
  48. count: currentCount - 1
  49. });
  50. this.timer = setTimeout(() => this.countDown(), 1000);
  51. } else {
  52. this.clearTimer();
  53. this.setState({
  54. isCounting: false,
  55. count: this.count
  56. });
  57. }
  58. }
  59.  
  60.  
  61. render() {
  62. let {children, defaultText} = this.props;
  63. let {isCounting, count} = this.state;
  64. return (
  65. children
  66. ? React.cloneElement(React.Children.only(children), {
  67. className: 'countdown-button',
  68. onClick: () => this.onClickHandler()
  69. }, isCounting ? count + 's' : defaultText)
  70. : <button
  71. className="countdown-button"
  72. onClick={this.onClickHandler}>
  73. {isCounting ? count + 's' : defaultText}
  74. </button>
  75. );
  76. }
  77. }
  78.  
  79. CountDown.defaultProps = {
  80. defaultText: 'click me'
  81. };
Add Comment
Please, Sign In to add comment