需求:实现一个时间打卡签到按钮。
实现方法:每隔一秒钟获取一下当前时间。
实现代码如下:
Column(){
Text(this.curTime)
.fontColor('#FFFFFF')
.fontWeight(600)
.fontSize('32vp')
Text('上班打卡')
.fontColor('#FFFFFF')
}
.width('170vp')
.height('170vp')
.justifyContent(FlexAlign.Center)
.alignItems(HorizontalAlign.Center)
.backgroundImage($r('app.media.check_signin'))
.backgroundImageSize({ width: StyleConstants.FULL_PARENT,height: StyleConstants.FULL_PARENT })
@State curTime:string | null = null;
@State time:number | null = null;
// 更新时间
updateTime(){
const now = new Date();
const hours = String(now.getHours()).padStart(2, '0');
const minutes = String(now.getMinutes()).padStart(2, '0');
const time = `${hours}:${minutes}` as string;
this.curTime = time;
}
aboutToAppear():void {
this.updateTime();
// 每秒更新一次时间
this.time = setInterval(()=>{
this.updateTime()
}, 1000);
}
aboutToDisappear():void {
// 清除定时器
clearInterval(this.time)
}