大致的原因推测可能是因为aboutToAppear在build之前,目前在aboutToAppear中加setTimeout可以解决该问题,setTimeout感觉无法完全保证将动画执行放到build后,想咨询下有没有更优的解决方案
@Component
export struct Block {
@Prop blockWidth: Length = 40
@Prop blockHeight: Length = 40
@Prop needDynamics: boolean = true
@Prop blockRadius: Resource | number = $r('app.float.radiusS')
@State opacityValue: number = this.needDynamics ? 0.4: 1
startAnimation () {
if (!this.needDynamics) return
animateTo({
playMode: PlayMode.Alternate,
iterations: -1,
duration: 1000,
}, () => {
this.opacityValue = 1
})
}
aboutToAppear(): void {
// 不加setTimeout动画无效,setTimeout感觉无法完全保证将动画执行放到build后
setTimeout(() => {
this.startAnimation()
}, 0)
}
build() {
Column()
.width(this.blockWidth)
.height(this.blockHeight)
.borderRadius(this.blockRadius)
.backgroundColor($r('app.color.fill2'))
.opacity(this.opacityValue)
}
}
可以使用onAppear方法放在组件上,组件完成显示的时候会调用。参考:
https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-universal-events-show-hide-V5\#示例