import { Component } from "react";
class Clock extends Component {
  constructor() {
    super();
    this.state = {
      date: new Date(),
      timer: null,
    };
  }
  componentDidMount() {
    // this.startEvent();
  }
  componentDidUpdate() {}
  componentDidUnMount() {}
  handleClick = () => {
    if (this.state.timer) {
      this.event();
    } else {
      this.startEvent();
    }
  };
  startEvent() {
    let time1;
    this.timer = time1 = setInterval(() => {
      this.setState(() => ({
        date: new Date(),
        timer: time1,
      }));
    }, 1000);
  }
  /**
   * 类组件中
   * this指向问题
   * 第一种：call bind apply
   * 第二种：直接调用 进入页面就会触发
   * 第三种：箭头函数:箭头函数没有this指向 this如果指向  只会指向它的上级/父级
   */
  event = () => {
    console.log(this, "this");
    clearInterval(this.state.timer);
    this.setState({
      timer: null,
    });
  };
  render() {
    return (
      <>
        <h2>计时器</h2>
        <p>初始事件：{this.state.date.toLocaleString()}</p>
        <button onClick={this.handleClick}>点我</button>
      </>
    );
  }
}
export default Clock;
