
##HarmonyOS Next快速入门##HarmonyOS应用开发##教育##
@Prop装饰器:父子单向同步
@Link装饰器:父子双向同步
@Prop装饰的变量和父组件建立单向的同步关系:
@Link装饰的变量与其父组件中的数据源共享相同的值。
总结
@Prop装饰变量限制条件:
@Link装饰变量限制条件:
@Prop变量装饰器必须指定类型,允许装饰的变量类型如下所示:
@Prop和数据源类型需要相同,有以下三种情况:
Prop支持联合类型实例:
@Prop支持联合类型和undefined和null,在下面的示例中,animal类型为Animals | undefined,点击父组件Zoo中的Button改变animal的属性或者类型,Child中也会对应刷新。
Link支持联合类型实例:
@Link支持联合类型和undefined和null,在下面的示例中,name类型为string | undefined,点击父组件Index中的Button改变name的属性或者类型,Child中也会对应刷新。
代码实例
PropLinkPage
import { LinkComponent } from './components/LinkComponent';
import { PropComponent } from './components/PropComponent';
@Entry
@Component
struct PropLinkPage {
@State message: string = '第2节 @Prop和@Link';
@State stateCount:number=0;
build() {
Column({space:10}) {
Text(this.message)
.fontSize(20)
.fontWeight(FontWeight.Bold)
Button('增加次数').onClick(()=>{
this.stateCount++
})
Text('stateCount='+this.stateCount)
PropComponent({propCount:this.stateCount})
LinkComponent({linkCount:this.stateCount})
}
.height('100%')
.width('100%')
}
}PropComponent
@Component
export struct PropComponent{
@Prop propCount:number=0
build() {
Column({space:10}){
Text('Prop子组件')
Button('增加次数').onClick(()=>{
this.propCount++
})
Text('propCount='+this.propCount)
}
.width('100%')
.padding(10)
.backgroundColor(Color.Orange)
}
}LinkComponent
@Component
export struct LinkComponent{
@Link linkCount:number
build() {
Column({space:10}){
Text('Link子组件')
Button('增加次数').onClick(()=>{
this.linkCount++
})
Text('linkCount='+this.linkCount)
}
.width('100%')
.padding(10)
.backgroundColor(Color.Pink)
}
}原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。