美文网首页
React 时钟组件

React 时钟组件

作者: 小黑哥啊哈哈 | 来源:发表于2019-04-09 19:48 被阅读0次
    import React from 'react';
    
    class Clock extends React.Component {
    
      constructor(props) {
        super(props);
        this.state = this.getTime();
      }
    
      componentDidMount() {
        this.setTimer();
      }
    
      componentWillUnmount() {
        if (this.timeout) {
          clearTimeout(this.timeout);
        }
      }
    
      setTimer() {
        clearTimeout(this.timeout);
        this.timeout = setTimeout(this.updateClock.bind(this), 1000);
      }
    
      updateClock() {
        this.setState(this.getTime, this.setTimer);
      }
    
      getTime() {
        const currentTime = new Date();
        return {
          hours: currentTime.getHours(),
          minutes: currentTime.getMinutes(),
          seconds: currentTime.getSeconds(),
          ampm: currentTime.getHours() >= 12 ? 'pm' : 'am'
        }
      }
    
      render() {
        const {hours, minutes, seconds, ampm} = this.state;
        return (
          <div className="clock">
            {
              hours == 0 ? 12 :
                (hours > 12) ?
                  hours - 12 : hours
            }:{
              minutes > 9 ? minutes : `0${minutes}`
            }:{
              seconds > 9 ? seconds : `0${seconds}`
            } {ampm}
          </div>
        )
      }
    }
    
    export default Clock
    

    相关文章

      网友评论

          本文标题:React 时钟组件

          本文链接:https://www.haomeiwen.com/subject/itziiqtx.html