赞
踩
意义:
可实现父类和子对象中变量的自由绑定。
@Observed应用于类,表示该类中的数据变更被UI页面管理,例如:@Observed class ClassA {}。
@ObjectLink应用于被@Observed所装饰类的对象(变量),例如:@ObjectLink a: ClassA。
@Observed 用于类,@ObjectLink 用于变量。
@ObjectLink装饰的变量类型必须为类(class type)。
@ObjectLink装饰的对象变量是不可变的(immutable),但可以修改对象里面变量的值。
@ObjectLink装饰的变量不可设置默认值。
@ObjectLink装饰的变量是私有变量,只能在组件内访问。
示例:
- //父组件ViewB中的类对象ClassB,其包含的对象ClassA与子组件ViewA数据同步时,通过ObjectLink将数据c值的变化状态通知给父组件同步变化。
- @Observed
- class ClassA {
- public name : string;
- public c: number;
- constructor(c: number, name: string = 'OK') {
- this.name = name;
- this.c = c;
- }
- }
-
- class ClassB {
- public a: ClassA;
- constructor(a: ClassA) {
- this.a = a;
- }
- }
-
- @Component
- struct ViewA {
- label : string = "ep1";
- @ObjectLink a : ClassA;
- build() {
- Column() {
- Text(`ViewA [${this.label}]: a.c=${this.a.c}`)
- .fontSize(20)
- Button(`+1`)
- .width(100)
- .margin(2)
- .onClick(() => {
- this.a.c += 1;
- })
- Button(`reset`)
- .width(100)
- .margin(2)
- .onClick(() => {
- this.a = new ClassA(0); // 错误:ObjectLink装饰的变量a是不可变的
- })
- }
- }
- }
-
- @Entry
- @Component
- struct ViewB {
- @State b : ClassB = new ClassB(new ClassA(10));
- build() {
- Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center}) {
- ViewA({label: "ViewA #1", a: this.b.a})
- ViewA({label: "ViewA #2", a: this.b.a})
-
- Button(`ViewB: this.b.a.c += 1` )
- .width(320)
- .margin(4)
- .onClick(() => {
- this.b.a.c += 1;
- })
- Button(`ViewB: this.b.a = new ClassA(0)`)
- .width(240)
- .margin(4)
- .onClick(() => {
- this.b.a = new ClassA(0);
- })
- Button(`ViewB: this.b = new ClassB(ClassA(0))`)
- .width(240)
- .margin(4)
- .onClick(() => {
- this.b = new ClassB(new ClassA(0));
- })
- }
- }
- }
![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
归纳总结:
1、@Observed 用于类,@ObjectLink 用于对象变量;
2、@ObjectLink修饰的变量初始化要求:@Observed修饰的父类中,@State、@Link、@StorageLink、@Provide或@Consume修饰的变量,并且用命名参数的形式。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。