1.子调用父的方法
子组件
父组件
2.使用emitter实现孙子传爷
孙子组件
import emitter from '@ohos.events.emitter';let event: emitter.InnerEvent = {eventId: 1,priority: emitter.EventPriority.HIGH};let eventData: emitter.EventData = {data: {"state": true,"item": JSON.stringify(this.item)}};// 孙子组件发送事件emitter.emit(event, eventData);
爷爷组件
aboutToAppear(): void {let event: emitter.InnerEvent = {eventId: 1};let callback = (eventData: emitter.EventData): void => {if (eventData && eventData.data) {this.item = JSON.parse(eventData.data.item)this.isShow = eventData.data.state}};// 爷爷组件监听事件emitter.on(event, callback);}
3.@Observed和@ObjectLink应用
@Observed
class Person {age: number = 18son: Son = new Son()
}@Observed
class Son {weight: number = 300
}@Component
struct MyButton {@ObjectLinkson: Sonbuild() {Column() {Button('son的weight' + this.son.weight).onClick(() => {// this.son.weight++})}}
}@Entry
@Component
struct Index {@Stateperson: Person = new Person()build() {Column() {MyButton({son: this.person.son}).onClick(() => {// this.person.son.weight++})Button('Personde age' + this.person.age).onClick(() => {this.person.age++})}}
}