react-webpack-flux-babel-natliu
Version:
react 全栈
63 lines (51 loc) • 1.29 kB
JSX
import React from 'react';
import Word from './Word';
import dateFormat from 'dateformat';
class Clock extends React.Component {
timer;
static defaultProps = {
format: 'yyyy-mm-dd HH:MM:ss',
onButtonClick: () => {}
}
constructor(props){
super(props)
this.state = {
time: this.getTime(),
count: 0
}
}
handleClick = () => {
let count = this.state.count + 1;
this.props.onButtonClick(count);
this.setState({
count: count
})
}
getTime(){
let now = new Date();
return dateFormat(now, this.props.format);
}
runClock(){
this.timer = setTimeout( () => {
this.setState({
time: this.getTime()
})
this.runClock()
}, 1000 );
}
componentDidMount(){
this.runClock()
}
componentWillUnmount(){
clearTimeout(this.timer);
}
render(){
return (
<div id="clock">
<Word words="当地时间:" /><span className="clock-text">{this.state.time}</span>
<p><button onClick={this.handleClick}>点击次数({this.state.count})</button></p>
</div>
);
}
}
export default Clock;