在線看私人不收費(fèi)不登錄網(wǎng)絡(luò)優(yōu)化工程師簡(jiǎn)歷
State裝飾器,
State裝飾的變量,稱為狀態(tài)變量,與聲明式范式中的其他被裝飾變量一樣,是私有的,只能從組件內(nèi)部訪問,在聲明時(shí),必須指定其類型和本地初始化。
Provide裝飾器和@Consume裝飾器,
其中@provide裝飾的變量是在祖先節(jié)點(diǎn)中,可以理解為被‘提供’給后代的狀態(tài)變量。@Consume裝飾的變量是在后代組件中,去綁定祖先節(jié)點(diǎn)提供的變量。
@Provide和@Consume可以通過相同的變量名或者相同的變量別名綁定,變量類型必須相同
// 通過相同的變量名綁定
@Provide a: number = 0;
@Consume a: number;// 通過相同的變量別名綁定
@Provide('a') b: number = 0;
@Consume('a') c: number;
實(shí)例
// 孫組件
@Component
struct CountDownComponentB {@Consume count: number;build() {Column() {Text(`這是孫組件的值:${this.count},改變會(huì)影響到父組件。`)Row(){Button(`+1`).onClick(() => {this.count += 1})Button(`-1`).onClick(() => {this.count -= 1})}.justifyContent(FlexAlign.SpaceEvenly).width("100%")}}
}// 子組件
@Component
struct CountDownComponentA {build() {Column() {// 孫組件CountDownComponentB()}}
}// 父組件
@Entry
@Component
struct ParentComponent {@Provide count: number = 10;build() {Column() {Text(`這是父組件的值:${this.count},改變會(huì)傳給孫組件。`)Row(){Button(`+1`).onClick(() => {this.count += 1;})Button(`-1`).onClick(() => {this.count -= 1;})}.justifyContent(FlexAlign.SpaceEvenly).width("100%")// 子組件CountDownComponentA()}}
}
watch裝飾器:狀態(tài)變量更改通知
@watch應(yīng)用于對(duì)狀態(tài)變量的監(jiān)聽。如果開發(fā)者需要關(guān)注某個(gè)狀態(tài)變量的值是否改變,可以使用@watch為狀態(tài)變量設(shè)置回調(diào)函數(shù)
當(dāng)狀態(tài)變量變化時(shí),@watch回調(diào)方法將被調(diào)用。@watch在ARKUI框架內(nèi)吧判斷數(shù)值有無(wú)更新,使用的是嚴(yán)格相等===,當(dāng)在嚴(yán)格相等為false的情況下,就會(huì)觸發(fā)@watch的回調(diào)。
@watch可用于購(gòu)物車計(jì)算總價(jià),或者實(shí)現(xiàn)計(jì)算器功能等
(ChangedPropertyName?:string)=>void
建議開發(fā)者避免無(wú)限循環(huán)。循環(huán)可能是因?yàn)樵?#64;watch的回調(diào)方法里面直接或者間接地修改了同一個(gè)狀態(tài)變量引起的,未來避免循環(huán)的產(chǎn)生,建議不要在@watch的回調(diào)方法里修改當(dāng)前裝飾的狀態(tài)變量
/*
- @Watch 修飾 狀態(tài)數(shù)據(jù)
- 函數(shù)中,不要修改被監(jiān)視的狀態(tài)變量。 我們要操作的是其他的業(yè)務(wù)邏輯
- */
@Entry
@Component
struct WatchDct {
@State @Watch(‘change’) count: number = 1
@State @Watch(‘change’) pow: number = 2
@State res: number = 1
change() {
this.res = Math.pow(this.count, this.pow)
}
build() {
Row() {
Column() {
Text(‘基數(shù):’ + this.count)
.fontSize(50)
.onClick(() => {
this.count++
})
Divider()Text(`次冪:${this.pow}`).fontSize(50).onClick(() => {this.pow++})Divider()Text("結(jié)果:" + this.res).fontSize(50)}.width('100%')
}
.height('100%')
}
}