目录

How do I resolve the issue where clicking the child component area triggers the parent component's click event?

Symptom

When enabled is set to false, clicking the Button component causes its parent component's click event to be triggered.

Solution

Wrap the Button component with a container component and set hitTestBehavior to HitTestMode.Block, which can prevent event bubbling. Refer to the code snippet below.

@Entry
@Component
struct TouchExample {
  @State text: string = 'Parent component'
  @State parentComponentResponse: string = 'Response times of parent component'
  @State parentComponentResponseNum: number = 0

  build() {
    Column() {
      Column(){
        Text(this.text).margin({bottom: 20})
        Text(this.parentComponentResponse + ':' + `${this.parentComponentResponseNum}`)
        Row(){
          //Wrap a container component around the Button component and set the hitTestBehavior property to HitTestMode.Block, which can prevent event bubbling.
          Button('Disable sub components').height(40).width(100).margin({top: 20})
        }
        .hitTestBehavior(HitTestMode.Block)
      }.onClick((e) => {
        this.parentComponentResponseNum ++;
      })
      .width('80%')
      .height('30%')
      .backgroundColor(Color.Gray)
    }
    .width('100%')
    .padding(30)
  }
}

Reference

Hit Test Control