Guest User

Untitled

a guest
Feb 16th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.59 KB | None | 0 0
  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import './index.css';
  4. import * as serviceWorker from './serviceWorker';
  5.  
  6. class TimerWrapper extends React.Component {
  7. constructor(props) {
  8. super(props);
  9. this.startTimer = this.startTimer.bind(this);
  10. this.state = {
  11. timeLeft: null, // Указывает на оставшееся время. Изначально равен null
  12. timer: null // Отсылается на наш таймер. Изначально равен null
  13. };
  14. }
  15.  
  16. startTimer(timeLeft) { // Вызывается при нажатии на button
  17. clearInterval(this.state.timer); // Избавляемся от запусков нескольких таймеров одновременно при нажатии на разные кнопки
  18. let timer = setInterval(() => {
  19. let timeLeft = this.state.timeLeft - 1; // Отнимает 1 секунду от оставшегося времени
  20. if (timeLeft === 0) { // Если оставшееся время равно 0,
  21. clearInterval(timer); // очищаем таймер, чтоб таймер не уходил в минус
  22. }
  23. this.setState({
  24. timeLeft: timeLeft // timeLeft из строки 10 равен timeLeft из строки 17
  25. });
  26. }, 1000);
  27. return this.setState({timeLeft: timeLeft, timer: timer});
  28. }
  29.  
  30. render() {
  31. return(
  32. <div>
  33. <h2>Timer</h2>
  34. <div>
  35. <Button time = '5' startTimer = {this.startTimer}/>
  36. <Button time = '10' startTimer = {this.startTimer}/>
  37. <Button time = '15' startTimer = {this.startTimer}/>
  38. </div>
  39. <TimerDisplay timeLeft = {this.state.timeLeft}/>
  40. <audio id = "end" preload = "auto" src = "../media/Barely Alive - Doggo.mp3"></audio>
  41. </div>
  42. )
  43. }
  44. }
  45.  
  46. class Button extends React.Component {
  47. handleStartTimer() {
  48. return this.props.startTimer(this.props.time)
  49. }
  50. render() {
  51. return <button onClick = {this.handleStartTimer.bind(this)}>
  52. {this.props.time} секунд</button>
  53. }
  54. }
  55.  
  56. class TimerDisplay extends React.Component {
  57. render() {
  58. if (this.props.timeLeft === 0) {
  59. document.getElementById("end").play()
  60. }
  61. if (this.props.timeLeft === 0 || this.props.timeLeft === null) {
  62. return <div></div>
  63. }
  64. return <h1>Осталось {this.props.timeLeft} секунд</h1>
  65. }
  66. }
  67.  
  68.  
  69. ReactDOM.render(<TimerWrapper />, document.getElementById('root'));
  70.  
  71. serviceWorker.unregister();
Add Comment
Please, Sign In to add comment