import React from 'react'; require('./index.css'); const initCount = -1; export default class ClockComponent extends React.Component{ constructor(props){ super(props); this.state = { count : initCount, timer : null }; this.time = 1000; this.beginCountBack = this.beginCountBack.bind(this) } componentWillMount(){ console.log("clock componentWillMount") let {totalTime} = this.props; if(totalTime && totalTime > 0){ this.setState({ count : totalTime },()=>{ this.beginCountBack() }) } } componentWillReceiveProps(){ console.log("clock componentWillReceiveProps") } componentWillUnmount(){ console.log("clock componentWillUnmount") window.clearTimeout(this.state.timer); this.setState({ timer : null, count : initCount }) } beginCountBack(){ let {callback} = this.props; let that = this; console.log("timer ",this.state.timer); if(!this.state.timer && this.state.count >= 0){ let count = this.state.count - 1; console.log("count ",count," ",this.state.count); this.state.timer = window.setTimeout(()=>{ if(count >= 0){ window.clearTimeout(that.state.timer); that.setState({ timer : null, count : count },()=>{ that.beginCountBack(); }) }else{ //倒计时结束 window.clearTimeout(that.state.timer); that.setState({ timer : null },()=>{ console.log("倒计时结束"); callback(); }) } },this.time) } } render(){ let props = this.props; return( <div className={"clockComponent font32"} style={props.style}> { props.text ? <span className={"clockText"}>{props.text}</span> : <img className={"clockIcon"} src={UTILPATH.localImg.clockIcon} alt=""/> } <span className={"clockTime"}>{this.state.count}s</span> </div> ) } }