#鸿蒙通关秘籍#如何在HarmonyOS中处理组件的获焦和失焦事件?

HarmonyOS
2024-12-04 14:34:24
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
Y影刃UI

在HarmonyOS中,通过onFocusonBlur事件可以监听组件的获焦和失焦。在组件中绑定这些事件,当组件获得焦点时,onFocus会被调用;而失去焦点时,onBlur会被调用。以下是一个简单的示例,演示如何使用这两个事件来改变按钮的背景色:

@Entry
@Component
struct FocusEventExample {
  @State oneButtonColor: Color = Color.Gray;
  @State twoButtonColor: Color = Color.Gray;
  build() {
    Column({ space: 20 }) {
      Button('First Button')
        .width(260)
        .height(70)
        .backgroundColor(this.oneButtonColor)
        .fontColor(Color.Black)
        .onFocus(() => {
          this.oneButtonColor = Color.Green;
        })
        .onBlur(() => {
          this.oneButtonColor = Color.Gray;
        })
      Button('Second Button')
        .width(260)
        .height(70)
        .backgroundColor(this.twoButtonColor)
        .fontColor(Color.Black)
        .onFocus(() => {
          this.twoButtonColor = Color.Green;
        })
        .onBlur(() => {
          this.twoButtonColor = Color.Gray;
        })
    }.width('100%').margin({ top: 20 })
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
分享
微博
QQ
微信
回复
2024-12-04 16:18:27
相关问题
HarmonyOS RichEditor /问题
1144浏览 • 1回复 待解决
HarmonyOS TextInput意外
964浏览 • 1回复 待解决
应用通用及走方式如何实现
2808浏览 • 1回复 待解决
restartApp在应用非时无法使用
921浏览 • 1回复 待解决
如何屏蔽方向键走事件
2508浏览 • 1回复 待解决