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

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;
      }
    });
  }
}
分享
微博
QQ
微信
回复
2024-12-04 17:04:07
相关问题
HarmonyOS onClick事件如何阻止事件冒泡
178浏览 • 1回复 待解决