2024年9月19日
鸿蒙开发之状态变量
5.1.2. @Prop
@Prop
用于装饰子组件的状态变量,@Prop
装饰的变量会同步父组件的状态,但只能单向同步,也就是父组件的状态变化会自动同步到子组件,而子组件的变化不会同步到父组件。

- 父组件
@Entry
@Component
struct Parent{
@State count: number = 1;
build(){
Column(){
Child({ count: this.count });
}
}
}
- 子组件
@Component
export struct Child{
@Prop count: number;
build(){
Text('prop.count: ' + this.count);
}
}
需要注意的是:@Prop
装饰的变量必须初始化,要么自己组件本地初始化,要么通过父组件传参进行初始化。
5.1.3. @Link
@Link
用于装饰子组件的状态变量,@Prop
变量同样会同步父组件状态,但是能够双向同步。也就是父组件的变化会同步到子组件,而子组件的变化也会同步到父组件。

- 父组件
@Entry
@Component
struct Parent{
@State count: number = 1;
build(){
Column(){
Child({ count: $count });
}
}
}
- 子组件
@Component
export struct Child{
@Link count: number;
build(){
Text('link.count: ' + this.count);
}
}
需要注意的是:@Link
装饰的变量不允许本地初始化,只能由父组件通过传参进行初始化,并且父组件必须使用$变量名
的方式传参,以表示传递的是变量的引用。