
##HarmonyOS Next实战##HarmonyOS SDK应用服务##教育##
参考资料:
在ArkUI中,UI显示的内容均为组件,由框架直接提供的称为系统组件,由开发者定义的称为自定义组件。进行UI界面开发时,不仅要组合使用系统组件,还需考虑代码的可复用性、业务逻辑与UI的分离,以及后续版本的演进等因素。因此,将UI和部分业务逻辑封装成自定义组件是不可或缺的能力。
自定义组件具有以下特点:
自定义组件是如此的常见,那么在父子组件间,就不可避免地会出现函数调用的问题。例如:父组件如何调用子组件的函数?子组件又如何调用父组件的函数?这是我们在项目开发中,往往不可避免会遇到的问题。
父子组件间调用函数是常见的交互需求,主要用于实现组件间的通信和功能协作。父子组件间调用函数的常见场景:
以下为实战代码示例:
父组件调用子组件函数
@Entry
@Component
struct CallSubComponentMethodPage {
private childController = new ChildController()
private count: number = 0
build() {
Column({ space: 10 }) {
Text('CallSubComponentMethod Page')
.fontSize(20)
.fontWeight(FontWeight.Bold)
Button('CallSubComponentMethod').onClick(() => {
this.count++
this.childController.changeText(`this is text from parent, and count = ${this.count}`)
})
Child({ childController: this.childController })
}
.height('100%')
.width('100%')
}
}
//定义controller对象
class ChildController {
changeText = (value: string) => {
}
}
@Component
struct Child {
@State private text: string = 'this is child text'
childController: ChildController = new ChildController();
aboutToAppear() {
//给childController对应的方法赋值
this.childController.changeText = this.changeText
}
//封装的能力
private changeText = (value: string) => {
this.text = value
}
build() {
Column() {
Text(this.text)
}
.backgroundColor('#EEEEEE')
.width('90%')
.height(100)
.justifyContent(FlexAlign.Center)
}
}子组件调用父组件函数
@Entry
@Component
struct CallParentComponentMethodPage {
@State sonClickCount: number = 0
build() {
Column({ space: 10 }) {
Text('CallParentComponentMethod Page')
.fontSize(20)
.fontWeight(FontWeight.Bold)
Text(`sonClickCount = ${this.sonClickCount}`)
Son({
onSonClick: (count: number) => {
this.sonClickCount = count
}
})
}
.height('100%')
.width('100%')
}
}
@Component
struct Son {
private count: number = 0
@Require onSonClick: (count: number) => void = (count: number) => {
}
build() {
Column({ space: 10 }) {
Text('Son Component')
Button('Son Click').onClick(() => {
this.count++
this.onSonClick(this.count)
})
}
.backgroundColor('#EEEEEE')
.width('90%')
.height(200)
.padding(10)
}
}原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。