設置本機外網(wǎng)ip做網(wǎng)站技術培訓
一、自定義組件
1、自定義組件
自定義組件,最基礎的結構如下:
@Component
struct Header {build() {}
}
提取頭部標題部分的代碼,寫成自定義組件。
1、新建ArkTs文件,把Header內(nèi)容寫好。
2、在需要用到的地方,導入引用即可
@Component
export struct Header {private title: ResourceStr = ''build() {Row() {Text(this.title).fontWeight(FontWeight.Bold).fontSize(24)}.width('100%').margin({ bottom: 10 })}
}
import { Header } from "../conponents/CommonHeader"@Entry
@Component
struct Index {@Statebuild() { // UI描述,內(nèi)部聲明式UI結構Column({ space: 10 }) {Header({ title: "商品列表" })}.width('100%')}.backgroundColor('#f0f8ff').padding(20).width('100%').height('100%')}
}
2、構建函數(shù)?
如果是僅在該頁面內(nèi)部運用的組件,就可以用構建函數(shù)的方式來定義組件
分兩類:全局和局部,區(qū)別就是寫在struct函數(shù)外還是內(nèi),若是放在struct之內(nèi),就不需要些‘function’字段了
這樣封裝,就保證了代碼易讀易維護
3、公共樣式
類似的,樣式也可以這樣封裝
但是Styles只能封裝所有組件都有的公共屬性,那對于個別的如何處理呢
就需要用到Extend(注意:只能定義成全局的,不能寫在struct函數(shù)內(nèi)部)
二、狀態(tài)管理-裝飾器
1、@State
@State裝飾器官網(wǎng)文檔
@State類似于react中的UseState,只在組件內(nèi)部使用
@Entry
@Component
struct StatePage {@State message: string = "hello"build() {Column() {Text(this.message).fontSize(20).onClick(()=>{this.message = '測試'})}.width('100%')}
}
2、@Props
@Prop裝飾器官網(wǎng)文檔
父組件單向傳值給子組件,類似于react里的props參數(shù),可以理解為父組件參數(shù)拷貝一份給子組件
子組件數(shù)值的變化不會同步到父組件
//子組件
@Component
struct CountDownComponent {@Prop count: number = 0;costOfOneAttempt: number = 1;build() {Column() {if (this.count > 0) {Text(`You have ${this.count} Nuggets left`)} else {Text('Game over!')}// @Prop裝飾的變量不會同步給父組件Button(`Try again`).onClick(() => {this.count -= this.costOfOneAttempt;})}}
}//父組件
@Entry
@Component
struct ParentComponent {@State countDownStartValue: number = 10;build() {Column() {Text(`Grant ${this.countDownStartValue} nuggets to play.`)// 父組件的數(shù)據(jù)源的修改會同步給子組件Button(`+1 - Nuggets in New Game`).onClick(() => {this.countDownStartValue += 1;})// 父組件的修改會同步給子組件Button(`-1 - Nuggets in New Game`).onClick(() => {this.countDownStartValue -= 1;})CountDownComponent({ count: this.countDownStartValue, costOfOneAttempt: 2 })}}
}
3、@Link
變量與其父組件中對應的數(shù)據(jù)源建立雙向數(shù)據(jù)綁定
可以理解為父組件把地址給子組件,所以改變能夠同步
@Link裝飾器官網(wǎng)文檔
//子組件接收變量@Link count: number@Link costOfOneAttempt: number//調用子組件,因為是引用的方式,所以要加上$CountDownComponent({ count: $countDownStartValue})
4、@Provide 和 @Consume
應用于與后代組件的雙向數(shù)據(jù)同步,應用于狀態(tài)數(shù)據(jù)在多個層級之間傳遞的場景,實現(xiàn)跨層級傳遞
就是爺爺和孫子之間直接溝通
不需要一級一級的顯示傳參
@Provide裝飾的變量是在祖先組件中,@Consume裝飾的變量是在后代組件中
感覺很方便,但一般咱不用,因為比較消耗性能
@Entry
@ComponentV2
struct Parent {@Provider() str: string = 'hello';build() {Column() {Button(this.str).onClick(() => {this.str += '0';})Child()}}
}@ComponentV2
struct Child {@Consumer() str: string = 'world';build() {Column() {Button(this.str).onClick(() => {this.str += '0';})}}
}
5、@Observed 和 @ObjectLink
用于在涉及嵌套對象或數(shù)組的場景中進行雙向數(shù)據(jù)同步
因為對于非簡單類型,比如class、Object或者數(shù)組,是需要被@Observed裝飾的,否則將觀察不到其屬性的變化
/**子組件定義包包的類型*/
@Observed
class Bag {public id: number;public size: number;constructor(size: number) {this.id = NextID++;this.size = size;}
}
@Observed
class User {public bag: Bag;constructor(bag: Bag) {this.bag = bag;}
}/**子組件*/
@Component
struct ViewA {label: string = 'ViewA';//被引用的類需要用ObjectLink裝飾@ObjectLink bag: Bag;build() {Column() {Text(`ViewA [${this.label}] this.bag.size = ${this.bag.size}`).fontColor('#ffffffff').backgroundColor('#ff3d9dba').width(320).height(50).borderRadius(25).margin(10).textAlign(TextAlign.Center)}Button(`ViewA: this.bag.size add 1`).width(320).backgroundColor('#ff17a98d').margin(10).onClick(() => {this.bag.size += 1;})}
}
}/**父組件*/
@Entry
@Component
struct ViewB {@State user: User = new User(new Bag(0));build() {Column() {ViewA({ label: 'ViewA #1', bag: this.user.bag }).width(320)}}
}
三、頁面路由
把所有訪問記錄存在棧里,類似于出棧入棧,跳轉就添加一條記錄,回到上一頁就是把當前記錄彈出棧,就回到了上一頁(ps:頁面棧的最大容量是32)
如果新訪問的頁面是棧里存在的,把它挪到棧頂即可,這樣節(jié)省空間性能
1、跳轉
有兩種方式:保留訪問記錄就用pushUrl,如果要銷毀記錄,就用replaceUrl
import router from '@ohos.router';
class DataModelInfo {age: number = 0;
}class DataModel {id: number = 0;info: DataModelInfo|null = null;
}function onJumpClick(): void {// 在Home頁面中l(wèi)et paramsInfo: DataModel = {id: 123,info: {age: 20}};router.pushUrl({url: 'pages/Detail', // 目標urlparams: paramsInfo // 添加params屬性,傳遞自定義參數(shù)}, (err) => {if (err) {console.error(`跳轉失敗, ${err.code}, ${err.message}`);return;}console.info('跳轉成功!');})
}
2、回到上一頁
返回用即可
import router from '@ohos.router';
//回退到指定的home頁
router.back({url: 'pages/Home'
});
//不傳參,即是回退到上一頁
//router.back();
3、綜合小案例
跳轉到對應頁面
如果新建頁面時,選擇的是新建page,則自動配置路徑,若是選擇ArkTs,則是沒有的
import router from '@ohos.router';class RouterInfo {url: stringtitle: stringconstructor(url: string, title: string) {this.url = url;this.title = title}
}@Entry
@Component
struct Index {@State message: string = '頁面列表'private routers: RouterInfo[] = [new RouterInfo("pages/Shopping", "商品"),new RouterInfo("pages/Mine", "我的"),]build() {Column() {Text(this.message).fontSize(30)List({ space: 15 }) {ForEach(this.routers,(router: RouterInfo, index) => {ListItem() {this.RouterItem(router, index + 1)}})}}.width('100%')}@BuilderRouterItem(r: RouterInfo, i: number) {Row() {Text(i + '.').fontSize(20).fontColor(Color.White)Blank()Text(r.title).fontSize(20).fontColor(Color.White)}.width(120).padding(12).backgroundColor('#38f').borderRadius(20).onClick(() => {router.pushUrl({url: r.url,params: i},router.RouterMode.Single,err => {if (err) {console.log(`跳轉失敗${err.message}${err.code}`)}})})}
}
寫在最后,可結合Harmony_鴻蒙專欄閱讀