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 ( <>

计时器

初始事件:{this.state.date.toLocaleString()}

); } } export default Clock;