聊城做網站的公司咨詢最常用的幾個關鍵詞
狀態(tài)?@State:
在聲明式UI中,以狀態(tài)驅動視圖更新
- 狀態(tài)(State):指驅動視圖更新的數(shù)據(jù)(被裝飾器標記的變量)
- 視圖(View):基于UI描述渲染得到的用戶界面
使用示例:
@Entry
@Component
struct Index {// 使用狀態(tài)裝飾器@State message: string = 'Hello Word'build() {Column(){Text(this.message)}};
}
說明:
- @State裝飾器標記的變量初始化必須有值
- @State支持Object、Class、string、number、boolean、enum類型以及這些類型的數(shù)組
- 嵌套類型以及數(shù)組中的對象屬性無法觸發(fā)視圖更新(相當于淺層監(jiān)聽)
父子組件數(shù)據(jù)同步 @Prop和@Link:
對比:
@Prop | @Link | |
同步類型 | 單向同步 | 雙向同步 |
允許裝飾的變量類型 |
|
|
初始化方式 | 不允許子組件初始化 | 父子間傳遞,不允許子組件初始化 |
@Prop使用示例:
PS:@Prop定義的數(shù)據(jù)在子組件不能初始化
@Entry
@Component
struct Index {@State msg: string = 'Hello Word'build() {Column() {MsgModule({msg:this.msg})Button('更改文案').onClick(()=>{this.msg = 'Hello arkTs'})}}
}@Component
struct MsgModule {@Prop msg:stringbuild(){Text(this.msg).fontSize(30).fontColor('red')}
}
@Link使用示例:
PS:
- @Link定義的數(shù)據(jù)在子組件不能初始化
- @Link定義的數(shù)據(jù),父組件在使用時候,去掉"this."且前邊加"$"符號
@Entry
@Component
struct Index {@State msg: string = 'Hello Word'build() {Column() {MsgModule({msg: $msg})}}
}@Component
struct MsgModule {@Link msg:stringbuild(){Row(){Text(this.msg).fontSize(30).fontColor('red')Button('更改文案').onClick(()=>{this.msg = 'Hello arkTs'})}}
}
?@Provide和@Consume:(跨組件提供雙向的數(shù)據(jù)同步)
??@Provide定義的數(shù)組,其他組件在使用時候直接使用@Consume定義使用,不需要在調用組件時候進行參數(shù)傳遞
使用示例:
@Entry
@Component
struct Index {@Provide msg: string = 'Hello Word'build() {Column() {MsgBtnModule()}}
}@Component
struct MsgBtnModule {build(){Row(){MsgModule()}}
}@Component
struct MsgModule {@Consume msg: stringbuild(){Row(){Text(this.msg).fontSize(30).fontColor('red')Button('更改文案').onClick(()=>{this.msg = 'Hello arkTs'})}}
}
@ObjectLink和@Observed:(涉及嵌套對象或數(shù)組元素為對象的場景中進行雙向數(shù)據(jù)同步)
使用示例:
@Observed
class ArrInt {name: string = ""price: number = 0
}@Entry
@Component
struct Index {@State num:number = 0@State arr: ArrInt[] = [{name: '華為 Meta 50',price: 7999},{name: '華為 Meta 60',price: 8999},{name: '華為 Meta 60 pro',price: 9999},]build() {Column() {Text('漲價' + this.num.toString() + '次').fontSize(50).margin(20)ArrModule({num: $num, arr: $arr})}}
}@Component
struct ArrModule {@Link num: number@Link arr: ArrInt[]build(){Row(){List({space: 10}){ForEach(this.arr,(item: ArrInt) => {ListItem(){ArrItemModule({item:item, num: $num})}})}}}
}@Component
struct ArrItemModule {@ObjectLink item: ArrInt@Link num: numberbuild(){Column(){Text(this.item.name).fontSize(30).fontColor('red')Text(this.item.price.toString()).fontSize(30).fontColor('#000')Button('漲價').onClick(()=>{this.num += 1})}}
}