@Prop装饰器:父子单向同步
//父组件
let numberone: number
@Entry
@Component
struct Props {
@State message: string = 'Hello World'
@State count: number = 123 //prop 传递值
build() {
Row() {
Column() {
Text(this.message)
Button('update').onClick(() => {
this.count++
})
chind({ count: this.count })
}
.width('100%')
}
.height('100%')
}
}
@Component
struct chind {
@Prop count: number;
build() {
Row() {
Column() {
Text(this.count.toString() ?? '') //直接接收使用 修改的话facomonpnts state 不会改变
}
}
}
}
限制条件
- @Prop修饰复杂类型时是深拷贝,在拷贝的过程中除了基本类型、Map、Set、Date、Array外,都会丢失类型。
- @Prop装饰器不能在@Entry装饰的自定义组件中使用
@Link装饰器:父子双向同步
概述
@Link装饰的变量与其父组件中的数据源共享相同的值。
限制条件
@Link装饰器不能在@Entry装饰的自定义组件中使用。
//父组件
let numberone: number
@Entry
@Component
struct Props {
@State message: string = 'Hello World'
@State count: number = 123 //prop 传递值
build() {
Row() {
Column() {
Text(this.message)
Button('update').onClick(() => {
this.count++
})
chind({ count: this.count })
}
.width('100%')
}
.height('100%')
}
}
@Component
struct chind {
@Link count: number;
build() {
Row() {
Column() {
Text(this.count.toString() ?? '') //直接接收使用 update fa comonents state
.onClick(() => {
this.count--
})
}
}
}
}
@Provide装饰器和@Consume装饰器:与后代组件双向同步
应用于与后代组件的双向数据同步,应用于状态数据在多个层级之间传递的场景
//create user:16054;
//vriten :透传peosp数据 祖孙组件通信
// testinfo:。。。
@Entry
@Component
struct Propsmodel { //zu
@State message: string = 'Hello World'
@Provide reviewVotes: number = 0;
build() {
Row() {
Column() {
child1()
}
.width('100%')
}
.height('100%')
}
}
@Component
struct child1 {
build() {
Row() {
Column() {
// Text('1')
child2()
}
}
}
}
@Component
struct child2 {
@Consume reviewVotes: numberl
build() {
Row() {
Column() {
Text(this.reviewVotes.toString())
// Text('2')
}
}
}
}
@ObjectLink和@Observed类装饰器用于在涉及嵌套对象或数组的场景中进行双向数据同步:
限制条件
- 使用@Observed装饰class会改变class原始的原型链,@Observed和其他类装饰器装饰同一个class可能会带来问题。
- @ObjectLink装饰器不能在@Entry装饰的自定义组件中使用。
//create user:16054;
//vriten :嵌套类型
// testinfo:。。。
let NextID: number = 1;
class ClassA {
public id: number;
public c: number;
constructor(c: number) {
this.id = NextID++;
this.c = c;
}
}
@Observed
class ClassB {
public a: ClassA;
public b: number;
constructor(a: ClassA, b: number) {
this.a = a;
this.b = b;
}
}
@Entry
@Component
struct Nesting {
@State message: string = 'Hello World'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
}
.width('100%')
}
.height('100%')
}
}