
回复
本文补充记录一下V2装饰器
@Param 组件外部输入
@Once初始化同步一次
@Event 规范组件回调
@Param表示组件从外部传入的状态,使得父子组件之间的数据能够进行同步:
@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未被外部初始化,但本地有默认值时,会使用本地默认的函数进行处理。