鸿蒙Next嵌套组件点击事件传递

2025-06-27 22:39:14
106次阅读
0个评论

嵌套事件传递默认的是,当父view和子view都有点击事件时,点击子组件默认响应的是子组件的点击方法,鸿蒙提供了四种传递模式可以设置,如下: 点击.gif

@Entry
@ComponentV2
struct test3{
  @Local message1:string=''
  @Local message2:string=''
  @Local message3:string=''
  @Local message4:string=''
  build() {
    Column({space:20}){
      Row(){
        Text('Default:'+this.message1).fontSize(30).fontColor(Color.Red)
          .onClick(()=>{
            this.message1+='子'
          })
      }.width('100%').backgroundColor(Color.Gray).justifyContent(FlexAlign.Center)
      .onClick(()=>{
        this.message1+='父'
      })
      .onTouchIntercept((event : TouchEvent) => {
        //自身节点和子节点都响应触摸事件的命中测试,但会阻止被该节点屏蔽的其他节点的命中测试
        return HitTestMode.Default
      })
      Row(){
        Text('Block:'+this.message2).fontSize(30).fontColor(Color.Red)
          .onClick(()=>{
            this.message2+='子'
          })
      }.width('100%').backgroundColor(Color.Gray).justifyContent(FlexAlign.Center)
      .onClick(()=>{
        this.message2+='父'
      })
      //自身节点响应触摸事件的命中测试,但阻止被该节点屏蔽的子节点和其他节点的命中测试
      //父点击事件不响应 响应子组件
      .onTouchIntercept((event : TouchEvent) => {
        return HitTestMode.Block
      })
      Row(){
        Text('Transparent:'+this.message3).fontSize(30).fontColor(Color.Red)
          .onClick(()=>{
            this.message3+='子'
          })
      }.width('100%').backgroundColor(Color.Gray).justifyContent(FlexAlign.Center)
      .onClick(()=>{
        this.message3+='父'
      })
      //自身节点和子节点响应触摸事件的命中测试,并允许对被该节点屏蔽的其他节点进行命中测试
      .onTouchIntercept((event : TouchEvent) => {
        return HitTestMode.Transparent
      })
      Row(){
        Text('None:'+this.message4).fontSize(30).fontColor(Color.Red)
          .onClick(()=>{
            this.message4+='子'
          })
      }.width('100%').backgroundColor(Color.Gray).justifyContent(FlexAlign.Center)
      .onClick(()=>{
        this.message4+='父'
      })
      //自身节点不会响应触摸事件的命中测试,但子节点会对触摸事件进行命中测试。
      //子组件点击事件不响应 响应父组件
      .onTouchIntercept((event : TouchEvent) => {
        return HitTestMode.None
      })
    }.width('100%')
    .height('100%')
  }
}
收藏00

登录 后评论。没有帐号? 注册 一个。