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

auhgnixgnahz
发布于 2025-6-12 17:36
浏览
0收藏

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

@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%')
  }
}

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
分类
收藏
回复
举报
回复
    相关推荐