父组件中如何处理子组件内点击事件

父组件中如何处理子组件内点击事件

HarmonyOS
2024-01-19 15:43:57
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
swordxxx

在父组件中初始化子组件时,将父组件中定义的方法,传递给子组件,在子组件中调用该方法,类似于变量传递。

代码示例

class Model { 
  value: string = '' 
} 
 
@Entry 
@Component 
struct EntryComponent { 
  test() { 
    console.log('testTag test in my component'); 
  } 
 
  build() { 
    Column() { 
      MyComponent({ title: { value: 'Hello World 2' }, 
        count: 7, 
        click: this.test }) //初始化时传递定义的方法 
    } 
  } 
} 
 
@Component 
struct MyComponent { 
  @State title: Model = { value: 'Hello World' } 
  @State count: number = 0 
  click: () => void = () => { 
  }; 
  private toggle: string = 'Hello World' 
  private increaseBy: number = 1 
 
  build() { 
    Column() { 
      Text(`${this.title.value}`).fontSize(30) 
      Button(`Click to increase count=${this.count}`) 
        .margin(20) 
        .onClick(() => { 
          // 修改内部状态变量count 
          this.count += this.increaseBy 
          this.click(); 
        }) 
    } 
  } 
}
  • 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.
分享
微博
QQ
微信
回复
2024-01-19 21:28:20
相关问题
组件事件可以传到组件
1438浏览 • 1回复 待解决
组件事件能否到传递组件
2998浏览 • 1回复 待解决