Clock.jsx 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. import { Component } from "react";
  2. class Clock extends Component {
  3. constructor() {
  4. super();
  5. this.state = {
  6. date: new Date(),
  7. timer: null,
  8. };
  9. }
  10. componentDidMount() {
  11. // this.startEvent();
  12. }
  13. componentDidUpdate() {}
  14. componentDidUnMount() {}
  15. handleClick = () => {
  16. if (this.state.timer) {
  17. this.event();
  18. } else {
  19. this.startEvent();
  20. }
  21. };
  22. startEvent() {
  23. let time1;
  24. this.timer = time1 = setInterval(() => {
  25. this.setState(() => ({
  26. date: new Date(),
  27. timer: time1,
  28. }));
  29. }, 1000);
  30. }
  31. /**
  32. * 类组件中
  33. * this指向问题
  34. * 第一种:call bind apply
  35. * 第二种:直接调用 进入页面就会触发
  36. * 第三种:箭头函数:箭头函数没有this指向 this如果指向 只会指向它的上级/父级
  37. */
  38. event = () => {
  39. console.log(this, "this");
  40. clearInterval(this.state.timer);
  41. this.setState({
  42. timer: null,
  43. });
  44. };
  45. render() {
  46. return (
  47. <>
  48. <h2>计时器</h2>
  49. <p>初始事件:{this.state.date.toLocaleString()}</p>
  50. <button onClick={this.handleClick}>点我</button>
  51. </>
  52. );
  53. }
  54. }
  55. export default Clock;