HarmonyOS鸿蒙Next中api10怎么子组件调用父组件的方法?

HarmonyOS鸿蒙Next中api10怎么子组件调用父组件的方法? api9中,父组件存在onChange() 方法。

子组件调用时父组件方法时申明onChildChange: () => void

父组件传递子组件childTask({ onChildChange:this.onChange.bind(this) })

但这个写法到api10报错,一直提示我子组件的onChildChange方法没有初始化,我尝试过给加个默认方法,提示我void不能作为

onChildChange: () => void = this.defaultChange()
defaultChange(){
}

请教下怎么处理?


更多关于HarmonyOS鸿蒙Next中api10怎么子组件调用父组件的方法?的实战教程也可以访问 https://www.itying.com/category-93-b0.html

11 回复

可参考以下文档修改:语法规则

更多关于HarmonyOS鸿蒙Next中api10怎么子组件调用父组件的方法?的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


可以参考自定义弹窗的写法

controller?: CustomDialogController
// 若尝试在CustomDialog中传入多个其他的Controller,以实现在CustomDialog中打开另一个或另一些CustomDialog,那么此处需要将指向自己的controller放在所有controller的后面
cancel: () => void = () => {
}
confirm: () => void = () => {
}
builder: CustomDialogExample({
cancel: () => { this.onCancel() },
confirm: () => { this.onAccept() },
textValue: $textValue,
inputValue: $inputValue
}),

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-methods-custom-dialog-box-V5#customdialogcontroller

可以用emitter或者eventHub

参考:[https://developer.huawei.com/consumer/cn/forum/topic/0203148932614687019?fid=0109140870620153026](https://developer.huawei.com/consumer/cn/forum/topic/0203148932614687019?fid=0109140870620153026)

api10你们怎么申请的,我才api9

官网更新下deveco工具的版本就有了,我的工具是4.0。

官网才3.1啊,我的工具也是4.0,新建项目只能选到api 9,

定义一个方法类型,再在父类里将这个类型的句柄传递到子类,是否是一种方法

type sthChangeed = () => void
刚试了下,这么写报错,

解决了吗?

在HarmonyOS Next的API 10中,子组件调用父组件的方法可以通过@State@Prop装饰器实现。首先,在父组件中定义一个方法,并通过@State@Prop将其传递给子组件。子组件接收该方法后,在适当的地方调用即可。例如:

// 父组件
@Entry
@Component
struct ParentComponent {
  @State message: string = 'Hello from Parent';

  handleChildClick() {
    this.message = 'Child clicked!';
  }

  build() {
    Column() {
      Text(this.message)
      ChildComponent({ onChildClick: this.handleChildClick.bind(this) })
    }
  }
}

// 子组件
@Component
struct ChildComponent {
  @Prop onChildClick: () => void;

  build() {
    Button('Click Me')
      .onClick(() => {
        this.onChildClick();
      })
  }
}

通过这种方式,子组件可以调用父组件的方法。

回到顶部