#鸿蒙通关秘籍#如何在鸿蒙系统中实现按键事件的阻止冒泡?

HarmonyOS
2024-12-04 14:12:26
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
星辰巅PVT

使用stopPropagation()方法在按键事件中可以阻止冒泡,使得除了Button组件以外,父组件不会响应按键事件:

@Entry
@Component
struct KeyEventExample {
  @State buttonText: string = '';
  @State buttonType: string = '';
  @State columnText: string = '';
  @State columnType: string = '';

  build() {
    Column() {
      Button('onKeyEvent')
        .defaultFocus(true)
        .width(140).height(70)
        .onKeyEvent((event?: KeyEvent) => {
          if(event){
            if(event.stopPropagation){
              event.stopPropagation();
            }
            if (event.type === KeyType.Down) {
              this.buttonType = 'Down';
            }
            if (event.type === KeyType.Up) {
              this.buttonType = 'Up';
            }
            this.buttonText = 'Button: \n' +
                              'KeyType:' + this.buttonType + '\n' +
                              'KeyCode:' + event.keyCode + '\n' +
                              'KeyText:' + event.keyText;
          }
        });

      Divider();
      Text(this.buttonText).fontColor(Color.Green);

      Divider();
      Text(this.columnText).fontColor(Color.Red);
    }.width('100%').height('100%').justifyContent(FlexAlign.Center)
    .onKeyEvent((event?: KeyEvent) => {
      if(event){
        if (event.type === KeyType.Down) {
          this.columnType = 'Down';
        }
        if (event.type === KeyType.Up) {
          this.columnType = 'Up';
        }
        this.columnText = 'Column: \n' +
                          'KeyType:' + this.buttonType + '\n' +
                          'KeyCode:' + event.keyCode + '\n' +
                          'KeyText:' + event.keyText;
      }
    });
  }
}
  • 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.
分享
微博
QQ
微信
回复
2024-12-04 17:04:07
相关问题
HarmonyOS onClick事件如何阻止事件冒泡
938浏览 • 1回复 待解决