在react中插入计时器

class Counter extends React.Component{

constructor(props,context)
{
super(props,context)
this.state={
hou:0,
second:0,
minutes:0,
strikes:0,
}
this.timer=this.timer.bind(this)//否则this不对
}
timer(){
const nextstrikes =this.state.strikes+50;
this.setState({
hou:parseInt(nextstrikes/3600000)%24,
minutes:parseInt(nextstrikes/60000)%60,
second: parseInt(nextstrikes/1000)%60,
strikes:this.state.strikes+50
})
}
componentDidMount() {
setInterval(this.timer,50);
}//render结束后
render(){
return(
<div>
<h1>{this.state.hou}:{this.state.minutes}:{this.state.second}</h1>
</div>
);

 

}
}
ReactDOM.render(
<Counter/>,document.querySelector('#counter')

)


注意里面的定时函数得下面这样配套使用

var int=self.setInterval("clock()",50)

window.clearInterval(int)

posted @ 2020-03-15 14:14  whhhd  阅读(578)  评论(0编辑  收藏  举报