gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:23:43 26 4
gpt4 key购买 nike

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

>

我如何修改它以在 ReactJS 组件中工作?我对 React 很陌生,实现 javascript 函数的方法不太一样,所以我不能真正使用我找到的任何常规 JS 答案。这是我的类(class)中的代码:

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>
);
}
}

提前致谢

最佳答案

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

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(':');
}

关于javascript - 使用 ReactJS 以两位数显示 getHours() 和 getMinutes(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43827846/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com