本文补充记录一下 V2 装饰器 @Param 组件外部输入 @Once 初始化同步一次 @Event 规范组件回调
@Param 表示组件从外部传入的状态,使得父子组件之间的数据能够进行同步:
@Param 装饰的变量支持本地初始化,但是不允许在组件内部直接修改变量本身。
被 @Param 装饰的变量能够在初始化自定义组件时从外部传入,当数据源也是状态变量时,数据源的修改会同步给 @Param。
@Param 可以接受任意类型的数据源,包括普通变量、状态变量、常量、函数返回值等。
@Param 装饰的变量变化时,会刷新该变量关联的组件。
@Param 支持观测 number、boolean、string、Object、class 等基本类型以及 Array、Set、Map、Date 等内嵌类型。
对于复杂类型如类对象,@Param 会接受数据源的引用。在组件内可以修改类对象中的属性,该修改会同步到数据源。
@Param 的观测能力仅限于被装饰的变量本身。当装饰简单类型时,对变量的整体改变能够观测到;当装饰对象类型时,仅能观测对象整体的改变;当装饰数组类型时,能观测到数组整体以及数组元素项的改变;当装饰 Array、Set、Map、Date 等内嵌类型时,可以观测到通过 API 调用带来的变化。
@Param 支持 null、undefined 以及联合类型。
@Entry
@ComponentV2
struct test3{
@Local message:string='Hello World'
@Local once_message:string='Hello World'
build() {
Column({space:20}){
Text('父布局:'+this.message).fontSize(20).fontColor(Color.Red)
Text('父布局:'+this.once_message).fontSize(20).fontColor(Color.Red)
child1({childMsg:this.message,childOnceMsg:this.once_message})
Button('刷新').onClick(()=>{
this.message='Hello HarmonyOS '+Math.floor(Math.random() * 11)
this.once_message='Hello HarmonyOS '+Math.floor(Math.random() * 11)
})
}.width('100%')
.height('100%')
}
}
@ComponentV2
struct child1{
@Require @Param childMsg:string
@Require @Param childOnceMsg:string
build() {
child2({childMsg:this.childMsg,childOnceMsg:this.childOnceMsg})
}
}
@ComponentV2
struct child2{
@Require @Param childMsg:string
@Require @Param @Once childOnceMsg:string
build() {
Column(){
Text('子布局:'+this.childMsg).fontSize(20)
.onClick(()=>{
//Cannot assign to 'childMsg' because it is a read-only property
// this.childMsg=''
})
Text('子布局:'+this.childOnceMsg).fontSize(20)
}
}
}
复制代码
@Once 装饰器仅在变量初始化时接受外部传入值进行初始化,当后续数据源更改时,不会将修改同步给子组件:
@Once 必须搭配 @Param 使用,单独使用或搭配其他装饰器使用都是不允许的。
@Once 不影响 @Param 的观测能力,仅针对数据源的变化做拦截。
@Once 与 @Param 装饰变量的先后顺序不影响实际功能。
@Once 与 @Param 搭配使用时,可以在本地修改 @Param 变量的值。
@Event 的使用方法类似于 Java 中的接口回调
@Entry
@ComponentV2
struct test4{
@Local message:string='Hello World'
build() {
Column({space:20}){
Text('父布局:'+this.message).fontSize(20).fontColor(Color.Red)
child1({childMsg:this.message,changeMessage:(ms:string)=>{
this.message = ms;
}})
Button('刷新').onClick(()=>{
this.message='Hello HarmonyOS '+Math.floor(Math.random() * 11)
})
}.width('100%')
.height('100%')
}
}
@ComponentV2
struct child1{
@Require @Param childMsg:string
@Event changeMessage: (val: string) => void;
build() {
Text('子布局:'+this.childMsg).fontSize(20)
.onClick(()=>{
this.changeMessage('子组件修改返回')
})
}
}
复制代码
@Event 用于装饰组件对外输出的方法:
@Event 装饰的回调方法中参数以及返回值由开发者决定。
@Event 装饰非回调类型的变量不会生效。当 @Event 没有初始化时,会自动生成一个空的函数作为默认回调。
当 @Event 未被外部初始化,但本地有默认值时,会使用本地默认的函数进行处理。
评论