@Watch
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
class B { public c: number constructor(c: number) { this.c = c } } class Obj { public a: number public b: B constructor(a: number, b: B) { this.a = a this.b = b } } @Entry @Component struct WatchExample { // watch 可以监听组件状态 State | Link | Provide ...... @State @Watch('update') obj: Obj = new Obj(1, new B(2)) // watch的监听回调 update() { console.log('监听到obj的变化') } build() { Column() { Text('watch监听').fontSize(20) Child07({ obj: $obj }) }.width("100%") } } @Component export default struct Child07 { @Link obj: Obj build() { Column() { Text('子组件Child07获取父组件传递的数据obj:' + JSON.stringify(this.obj)) Button('修改父组件@Watch监听的数据').onClick((event: ClickEvent) => { // this.obj = { a: 20, b: { c: 30 } } this.obj.a += 100 // 无法深度监听 this.obj.b.c += 9 }) } .width('100%') .border({ width: 1, color: Color.White }) } } |
@Observed
示例场景:有一个动物小狗,小狗有一个主人,显示主人的年龄,加一个按钮更改主人的年龄。
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
@Entry @Component struct Index { @State dog: Animal = new Animal('Kit', 1, new Master('Lucy', 10)) build() { Column() { Text('主人信息:') Row() { Text('年龄:') Text(this.dog.master.age.toString()) }.margin({ bottom: 20 }) DogMasterInfo({ master: this.dog.master }) .margin({ bottom: 20 }) Button('改变主人年龄') .onClick(() => { this.dog.master.age += 1 }) } .width('100%') .padding(30) .alignItems(HorizontalAlign.Start) } } @Component struct DogMasterInfo { @ObjectLink master: Master build() { Column() { Text('主人信息:') Row() { Text('年龄:') Text(this.master.age.toString()) } } .width('100%') .alignItems(HorizontalAlign.Start) } } @Observed class Animal { public name: string public age: number public master: Master constructor(name: string, age: number, master: Master) { this.name = name this.age = age this.master = master } } @Observed class Master { public name: string public age: number constructor(name: string, age: number) { this.name = name this.age = age } } |