在父组件中初始化子组件时,将父组件中定义的方法,传递给子组件,在子组件中调用该方法,类似于变量传递。参考代码如下:
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();
})
}
}
}