HarmonyOS鸿蒙Next组件内转场动画,如何用条件控制是否进行转场动画
HarmonyOS鸿蒙Next组件内转场动画,如何用条件控制是否进行转场动画
有一个组件,使用了 transition 转场动画,但是希望可以控制,在某些情况下,不使用动画,直接出现/隐藏。目前测试发现,如果使用了动画出现,那么一定会使用动画隐藏,无法控制不使用动画隐藏。
@Component
struct DemoPage {
@State animated: boolean = true
@State show: boolean = false
build() {
NavDestination() {
Column() {
if (this.show) {
Column()
.width('60%')
.height(50)
.backgroundColor(Color.Red)
.transition(TransitionEffect.OPACITY.animation({duration: this.animated ? 1000 : 0}))
}
Button('show and animate')
.margin({top: 50})
.onClick(() => {
this.animated = true
this.show = true
})
Button('show and !animate')
.margin({top: 50})
.onClick(() => {
this.animated = false
this.show = true
})
Button('!show and animate')
.margin({top: 50})
.onClick(() => {
this.animated = true
this.show = false
})
Button('!show and !animate')
.margin({top: 50})
.onClick(() => {
this.animated = false
this.show = false
})
}
.width('100%')
.height('100%')
}.hideTitleBar(true)
}
}
更多关于HarmonyOS鸿蒙Next组件内转场动画,如何用条件控制是否进行转场动画的实战教程也可以访问 https://www.itying.com/category-93-b0.html
3 回复
可以参考这段代码:
@Component
struct DemoPage {
@State animated: boolean = true
@State show: boolean = false
build() {
NavDestination() {
Column() {
if (this.show) {
Column()
.width('60%')
.height(50)
.backgroundColor(Color.Red)
.transition(this.animated
?
TransitionEffect.OPACITY.animation({ duration: 1000 })
:
TransitionEffect.OPACITY.animation({ duration: 0 }).combine(TransitionEffect.IDENTITY)
)
}
Button('需要动画-显示')
.margin({ top: 50 })
.onClick(() => {
this.show = true
this.animated = true
})
Button('需要动画-隐藏')
.margin({ top: 50 })
.onClick(() => {
this.show = false
this.animated = true
})
Button('不需要动画-显示')
.margin({ top: 50 })
.onClick(() => {
this.show = true
this.animated = false
})
Button('不需要动画-隐藏')
.margin({ top: 50 })
.onClick(() => {
this.show = false
this.animated = false
})
}
.width('100%')
.height('100%')
}.hideTitleBar(true)
}
}
更多关于HarmonyOS鸿蒙Next组件内转场动画,如何用条件控制是否进行转场动画的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS中,转场动画可以通过transition
组件来实现。要在组件内控制是否进行转场动画,可以使用条件语句或状态变量来控制transition
组件的渲染与执行。
假设你有一个条件变量shouldAnimate
,用于控制是否执行转场动画,可以按如下方式实现:
@Entry
@Component
struct MyComponent {
@State shouldAnimate: boolean = true;
build() {
Column() {
if (this.shouldAnimate) {
// 使用transition组件包裹需要动画的元素
transition({ type: TransitionType.Insert, scale: { x: 0, y: 0 } }) {
Text('Animated Text')
.fontSize(30)
}
} else {
// 不执行动画,直接显示元素
Text('Static Text')
.fontSize(30)
}
Button('Toggle Animation')
.onClick(() => {
this.shouldAnimate = !this.shouldAnimate;
})
}
}
}
在这个示例中,shouldAnimate
状态变量控制是否执行转场动画。当shouldAnimate
为true
时,transition
组件会包裹Text
元素,执行插入动画;当shouldAnimate
为false
时,直接显示Text
元素,不执行动画。
通过这种方式,可以灵活控制是否执行转场动画。