使用ReactJS以两位数显示getHours()和getMinutes()

时间:2017-05-07 04:32:44

标签: javascript reactjs

我的活动时钟工作得很好,除了在早上时间,显示1:2:3时应显示01:02:03

如何修改它以在ReactJS组件中工作?我在React上很新,实现javascript功能的方法也不尽相同,所以我无法真正使用我发现的任何常规JS答案。这是我班上的代码:

class SidebarContent extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            date: new Date()
        };
    }

    componentWillUnmount() {
        clearInterval(this.timerID);
    }

    tick() {
        this.setState({date: new Date()});
    }

    getHours() {
        return this.state.date.getHours();
    }
    getMinutes() {
        return this.state.date.getMinutes();
    }

    getSeconds() {
        return this.state.date.getSeconds();
    }


    componentDidMount() {

       this.timerID = setInterval(() => this.tick(), 1000);
    }

    render() {

    return (
        <ul className="nav" ref={(c) => {this.nav = c; }}>
            <li className="today">
                <Row className="clock" center="xs">
                    <Row center="xs">
                        <span className="hours">{this.getHours()}</span>
                        <span>:</span>
                        <span className="min">{this.getMinutes()}</span>

                        <span className="sec">{this.getSeconds()}</span>
                    </Row>
                </Row>
                <Row className="date" center="xs">
                    <p className="today-is">{this.state.date.toDateString()}</p>
                </Row>
            </li>
        </ul>
      );
   }
}

提前致谢

5 个答案:

答案 0 :(得分:2)

如果您希望自己可以momentjs而忘记格式化内容。 momentjs将照顾到这一点。您只需要指定格式。我相信看起来比填充更清洁。

class SidebarContent extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            date: moment()
        };
    }

    componentWillUnmount() {
        clearInterval(this.timerID);
    }

    tick() {
        this.setState({date: moment()});
    }

    getTime() {
        return this.state.date.format('HH:mm:ss')
    }

    componentDidMount() {
        this.timerID = setInterval(() => this.tick(), 1000);
    }

    render() {

    return (
        <ul className="nav" ref={(c) => {this.nav = c; }}>
            <li className="today">
                <div className="clock" center="xs">
                    <div center="xs">
                        <span className="hours">{this.getTime()}</span>
                    </div>
                </div>
                <div className="date" center="xs">
                    <p className="today-is">
                    {this.state.date.format('ddd MMM DD YYYY')}</p>
                </div>
            </li>
        </ul>
      );
   }
}

这是同样的小提琴。 JSFiddle

答案 1 :(得分:1)

您可以使用lodash中的功能padStart。您可以安装整个lodash库或独立包lodash.padstart

要显示前导0,您可以执行以下操作:

&#13;
&#13;
// here you will import the function from the lodash package
// import padStart from 'lodash.padstart';
// OR
// import padStart from 'lodash/padstart';
const padStart = _.padStart;

class SidebarContent extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      date: new Date()
    };
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  tick() {
    this.setState({
      date: new Date()
    });
  }

  getHours() {
    return padStart(this.state.date.getHours(), 2, '0');
  }
  getMinutes() {
    return padStart(this.state.date.getMinutes(), 2, '0');
  }

  getSeconds() {
    return padStart(this.state.date.getSeconds(), 2, '0');
  }


  componentDidMount() {

    this.timerID = setInterval(() => this.tick(), 1000);
  }

  render() {

    return ( <
      ul className = "nav"
      ref = {
        (c) => {
          this.nav = c;
        }
      } >
      <
      li className = "today" >
      <
      div className = "clock"
      center = "xs" >
      <
      div center = "xs" >
      <
      span className = "hours" > {
        this.getHours()
      } < /span> <
      span >: < /span> <
      span className = "min" > {
        this.getMinutes()
      } < /span> <
      span >: < /span> <
      span className = "sec" > {
        this.getSeconds()
      } < /span> <
      /div> <
      /div> <
      div className = "date"
      center = "xs" >
      <
      p className = "today-is" > {
        this.state.date.toDateString()
      } < /p> <
      /div> <
      /li> <
      /ul>
    );
  }
}


ReactDOM.render( < SidebarContent / > , document.getElementById("app"));
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdn.jsdelivr.net/lodash/4.17.4/lodash.min.js"></script>

<div id="app" />
&#13;
&#13;
&#13;

答案 2 :(得分:1)

填充时间基本上是这样的:

if (seconds < 10) {
   return '0' + seconds;
} else {
   return '' + seconds;
}

const pad = (seconds < 10) ? '0' : '';
return pad + seconds;

总计:

getFormattedTime() {
    const {date} = this.state;
    const timeComponents = [date.getHours(), date.getMinutes(), date.getSeconds()];
    return timeComponents
        .map(component => {
            const pad = (component < 10) ? '0' : '';
            return pad + component;
        })
        .join(':');
}

答案 3 :(得分:-1)

这是我在倒数计时器应用程序中做到这一点的时间。这里给出了以秒为单位的时间,它返回一个JSON对象,它以两位数格式表示小时,分钟和秒。

  secondsToTime(secs) {
    let hours = `${constants.ZERO}${Math.floor(secs / (60 * 60))}`.slice(-2);

    let divisorForMinutes = secs % (60 * 60);
    let minutes = `${constants.ZERO}${Math.floor(divisorForMinutes / 60)}`.slice(-2);

    let divisorForSeconds = divisorForMinutes % 60;
    let seconds = `${constants.ZERO}${Math.ceil(divisorForSeconds)}`.slice(-2);

    let obj = {
      "h": hours,
      "m": minutes,
      "s": seconds
    };
    return obj;
  }

您可以访问这样的值。

var remainingTime = this.secondsToTime(timeInSeconds);
remainingTime["h"] // gives you hours
remainingTime["m"] // gives you minutes
remainingTime["s"] // gives you seconds

这种方法远比调用3个函数分别获得小时,分钟和秒更好,这对我来说有点尴尬。希望这可以帮助。快乐的编码!

答案 4 :(得分:-2)

React 普通的javascript。你绝对可以在那里使用任何普通的JavaScript。你的问题与反应无关,与javascript有关。 Date()方法返回一位数字。您需要以某种方式填充输出。见How to output integers with leading zeros in JavaScript