#鸿蒙通关秘籍#如何在HarmonyOS NEXT中防止触摸事件冒泡

HarmonyOS
2024-12-06 15:22:42
1137浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
数据小天才

在HarmonyOS NEXT开发中,当子组件触发触摸事件时,为了防止父组件的触摸事件也被触发,可以在子组件的onTouch回调中调用event.stopPropagation()来阻止事件冒泡。具体代码如下:

@Component
struct TouchEvent {
  @Consume isEnabled: boolean;
  @State parentCompResponseTimes: number = 0;
  @State childCompResponseTimes: number = 0;

  build() {
    Column() {
      Text("触摸事件阻止冒泡示例")
        .width('90%')
        .textAlign(TextAlign.Start)
      Column() {
        Text("父组件")
          .margin('10px')
        Row() {
          Text("父组件响应次数: ")
          Text(`${this.parentCompResponseTimes}`)
        }
        .margin({
          top: '10px',
          bottom: '10px'
        })

        Row() {
          Text("子组件响应次数: ")
          Text(`${this.childCompResponseTimes}`)
        }.margin({ bottom: '10px' })

        Text("子组件")
          .width(200)
          .height(50)
          .borderRadius(10)
          .fontColor(Color.White)
          .textAlign(TextAlign.Center)
          .backgroundColor('#0000FF')
          .onTouch((event) => {
            if (this.isEnabled) {
              event.stopPropagation();
            }
            this.childCompResponseTimes++;
          })
      }
      .width('90%')
      .height(150)
      .margin({ top: '20px' })
      .backgroundColor('#F0F0F0')
      .borderRadius(10)
      .alignItems(HorizontalAlign.Center)
      .onTouch(() => {
        this.parentCompResponseTimes++;
      })
    }
    .margin({ top: '30px' })
  }
}
  • 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.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
分享
微博
QQ
微信
回复
2024-12-06 17:49:59
相关问题