
回复
添加资源
添加资源将有机会获得更多曝光,你也可以直接关联已上传资源
去关联
在学习声明式UI框架ArkUI的过程中,会遇到装饰器的概念,不管是简单的示例页面还是复杂的大程序,都离不开装饰器的使用,为了帮助自己对装饰器有一个基本的了解,并能够熟练的使用,所以专门针对ets装饰器系统的学习了一下,并整理成简单的笔记,以便健忘的我随时回来复习一下。
本文主要介绍@State、@Prop和@Link,@State表示组件内部状态数据,@Prop装饰的变量必须是定义在子组件中,并且在父组件调用的时候进行参数赋值,@Link装饰的变量可以和父组件的@State变量建立双向数据绑定。
@State装饰的变量是组件内部的状态数据,当这些状态数据被修改时,将会调用所在组件的build方法进行UI刷新。
@State状态数据具有以下特征:
class Model {
value: string
constructor(value: string) {
this.value = value
}
}
@Entry
@Component
struct Index {
@State title: Model = { value: 'Introduction' }
@State index: number = 2
@State message: string = 'This is an example for State'
@State items : Array<string> = ['First item','Second item','Third item']
build() {
Row() {
Column() {
Text(this.index.toString())
.fontSize(50)
.width('100%')
Text(this.title.value)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.width('100%')
.textAlign(TextAlign.Start)
Text(this.message)
.fontSize(25)
.width('100%')
ForEach(this.items, item => {
Text(item.toString()).fontSize(18).padding(10)
.width('100%')
.textAlign(TextAlign.Start)
}, item => item.toString())
SubComponent({num: 20})
}
.width('100%')
}
.height('100%')
}
}
@Component
struct SubComponent {
@Prop num: number
build() {
Column() {
Text(`SubComponent num ${this.num} `).fontSize(28)
.fontColor(Color.White)
}
.width('100%')
.backgroundColor(Color.Gray)
}
}
上面示例,分别针对state修饰的变量按照class、number、string、Array<string>
类型进行了实践,需要注意的是必须本地初始化。
@Prop与@State有相同的语义,但初始化方式不同。@Prop装饰的变量必须使用其父组件提供的@State变量进行初始化,允许组件内部修改@Prop变量,但更改不会通知给父组件,即@Prop属于单向数据绑定。
@Prop状态数据具有以下特征:
@Entry
@Component
struct Index {
@State message: string = 'Prop'
build() {
Row() {
Column() {
Text(this.message)
.fontSize(50)
.fontWeight(FontWeight.Bold)
SubComponent({count : 20})
}
.width('100%')
}
.height('100%')
}
}
@Component
struct SubComponent {
@Prop count: number
build(){
Text("subcomponent member:" + this.count)
.fontSize(25)
}
}
需要注意的是,在子组件中prop变量不能初始化,在父组件调用时,必须给变量赋值。
@Link装饰的变量可以和父组件的@State变量建立双向数据绑定:
@Entry
@Component
struct Index {
@State count: number = 0
build() {
Row() {
Column() {
Text('count=' + this.count)
.fontSize(50)
.fontWeight(FontWeight.Bold)
SubComponent({ subCount: $count })
}
.width('100%')
}
.height('100%')
}
}
@Component
struct SubComponent {
@Link subCount: number
build() {
Button('subCount=' + this.subCount)
.margin(15)
.onClick(() => {
this.subCount += 1
})
}
}
需要注意的是,@Link变量不能在组件内部进行初始化,@State变量要通过’$'操作符创建引用。