今天遇到一个简单的小功能,看网上的一些方法感觉不太适合,所以就手敲了一个,直接上代码!!!
1 import React, { Component } from 'react'; 2 3 class NoTimeContent extends Component { 4 constructor(props) { 5 super(props) 6 this.state = { 7 day: 0, 8 hour: 0, 9 minute: 0,10 second: 011 }12 }13 render() {14 return (1516 21 )22 }23 24 componentDidMount() {25 const end = Date.parse(new Date('2018-11-29 24:00'))26 this.countFun(end);27 }28 29 //卸载组件取消倒计时30 componentWillUnmount(){31 clearInterval(this.timer);32 }33 34 countFun = (end) => {35 36 let now_time = Date.parse(new Date());37 var remaining = end - now_time;38 39 this.timer = setInterval(() => {40 //防止出现负数41 if (remaining > 1000) {42 remaining -= 1000;43 let day = Math.floor((remaining / 1000 / 3600) / 24);44 let hour = Math.floor((remaining / 1000 / 3600) % 24);45 let minute = Math.floor((remaining / 1000 / 60) % 60);46 let second = Math.floor(remaining / 1000 % 60);47 48 this.setState({49 day:day,50 hour:hour < 10 ? "0" + hour : hour,51 minute:minute < 10 ? "0" + minute : minute,52 second:second < 10 ? "0" + second : second53 })54 } else {55 clearInterval(this.timer);56 //倒计时结束时触发父组件的方法57 //this.props.timeEnd();58 }59 }, 1000);60 }61 62 }63 export default NoTimeContent;17 限时秒杀18 { this.state.day}天 { this.state.hour}:{ this.state.minute}:{ this.state.second}19
20