HarmonyOS NEXT開發(fā)之ArkTS自定義組件學(xué)習(xí)筆記
在HarmonyOS中,ArkTS提供了創(chuàng)建自定義組件的能力,允許開發(fā)者封裝和復(fù)用UI代碼。以下是關(guān)于自定義組件的詳細(xì)介紹,包括創(chuàng)建自定義組件、頁(yè)面和自定義組件的生命周期、自定義組件的自定義布局、凍結(jié)功能,以及代碼案例分析。
創(chuàng)建自定義組件
自定義組件是基于struct實(shí)現(xiàn)的,使用@Component裝飾器來標(biāo)識(shí)。每個(gè)自定義組件都必須實(shí)現(xiàn)build()方法,用于描述組件的UI結(jié)構(gòu)。
@Component
struct HelloComponent {
@State message: string = 'Hello, World!';
build() {
Row() {
Text(this.message)
.onClick(() => {
this.message = 'Hello, ArkUI!';
})
}
}
}
在其他文件中使用該自定義組件時(shí),需要使用export關(guān)鍵字導(dǎo)出,并在頁(yè)面中使用import導(dǎo)入該組件 。
頁(yè)面和自定義組件生命周期
頁(yè)面生命周期僅限于被@Entry裝飾的組件,而自定義組件的生命周期僅限于被@Component裝飾的組件。
onPageShow:頁(yè)面每次顯示時(shí)觸發(fā)。onPageHide:頁(yè)面每次隱藏時(shí)觸發(fā)。onBackPress:當(dāng)用戶點(diǎn)擊返回按鈕時(shí)觸發(fā)。aboutToAppear:組件即將出現(xiàn)時(shí)觸發(fā)。aboutToDisappear:組件即將銷毀時(shí)觸發(fā) 。
自定義組件的自定義布局
如果需要通過測(cè)算的方式布局自定義組件內(nèi)子組件的位置,可以使用onMeasureSize和onPlaceChildren接口。
@Component
struct CustomLayout {
@Builder doNothingBuilder() {};
@BuilderParam builder: () => void = this.doNothingBuilder;
@State startSize: number = 100;
result: SizeResult = { width: 0, height: 0 };
onMeasureSize(selfLayoutInfo: GeometryInfo, children: Array<Measurable>, constraint: ConstraintSizeOptions) {
let size = 100;
children.forEach((child) => {
let result: MeasureResult = child.measure({ minHeight: size, minWidth: size, maxWidth: size, maxHeight: size });
size += result.width / 2;
});
this.result.width = 100;
this.result.height = 400;
return this.result;
}
onPlaceChildren(selfLayoutInfo: GeometryInfo, children: Array<Layoutable>, constraint: ConstraintSizeOptions) {
let startPos = 300;
children.forEach((child) => {
let pos = startPos - child.measureResult.height;
child.layout({ x: pos, y: pos });
});
}
build() {
this.builder();
}
}
在這個(gè)例子中,CustomLayout組件通過onMeasureSize和onPlaceChildren設(shè)置了子組件的大小和位置 。
自定義組件凍結(jié)功能
從API version 12開始,@ComponentV2裝飾的自定義組件支持凍結(jié)功能。當(dāng)組件處于非激活狀態(tài)時(shí),狀態(tài)變量將不響應(yīng)更新。
@Entry@ComponentV2({ freezeWhenInactive: true })
struct FirstTest {
build() {
Column() {
Text(`From first Page ${book.page}`).fontSize(50)
Button('first page + 1').fontSize(30)
.onClick(() => {
book.page += 1;
})
Button('go to next page').fontSize(30)
.onClick(() => {
router.pushUrl({ url: 'pages/Page' });
})
}
}
}
在這個(gè)例子中,當(dāng)頁(yè)面A跳轉(zhuǎn)到頁(yè)面B時(shí),頁(yè)面A的狀態(tài)變?yōu)榉羌せ睿M件的更新將被凍結(jié) 。
通過這些功能,開發(fā)者可以創(chuàng)建可復(fù)用、響應(yīng)式且具有復(fù)雜布局的自定義組件,從而提升HarmonyOS應(yīng)用的開發(fā)效率和用戶體驗(yàn)。
自定義組件案例:訂單列表頁(yè)面
假設(shè)我們需要開發(fā)一個(gè)HarmonyOS應(yīng)用,其中包含一個(gè)訂單列表頁(yè)面。這個(gè)頁(yè)面將顯示一個(gè)訂單項(xiàng)的自定義組件,每個(gè)訂單項(xiàng)包含訂單編號(hào)、日期和訂單狀態(tài)。我們希望這個(gè)自定義組件是可重用的,以便在應(yīng)用的其他部分也可以使用它。
步驟 1: 創(chuàng)建自定義組件
首先,我們創(chuàng)建一個(gè)名為OrderItem的自定義組件,它將顯示單個(gè)訂單項(xiàng)的詳細(xì)信息。
// OrderItem.ets
@Component
export struct OrderItem {
@Prop orderId: string;
@Prop orderDate: string;
@Prop status: string;
build() {
Row() {
Text(this.orderId).width(200).height(60).fontSize(16).alignItems(HorizontalAlign.Start);
Text(this.orderDate).width(150).height(60).fontSize(14).alignItems(HorizontalAlign.Center);
Text(this.status).width(100).height(60).fontSize(14).alignItems(HorizontalAlign.End);
}.padding(10).backgroundColor(Color.White).border({ width: 1, color: Color.Grey });
}
}
在這個(gè)組件中,我們使用了@Prop裝飾器來定義屬性,這些屬性將由父組件傳遞。build()方法定義了訂單項(xiàng)的UI結(jié)構(gòu),使用了Row布局來水平排列訂單編號(hào)、日期和狀態(tài)。
步驟 2: 使用自定義組件
接下來,我們?cè)谟唵瘟斜眄?yè)面中使用OrderItem組件來顯示訂單數(shù)據(jù)。
// OrderList.ets
import { OrderItem } from './OrderItem';
@Entry
@Component
struct OrderList {
@State orders: Array<{ orderId: string; orderDate: string; status: string }> = [
{ orderId: '001', orderDate: '2024-04-01', status: 'Completed' },
{ orderId: '002', orderDate: '2024-04-02', status: 'Shipped' },
// 更多訂單...
];
build() {
Column() {
ForEach(this.orders, (order) => {
OrderItem({
orderId: order.orderId,
orderDate: order.orderDate,
status: order.status,
});
});
}.spacing(10).padding(10);
}
}
在OrderList組件中,我們定義了一個(gè)狀態(tài)變量orders來存儲(chǔ)訂單數(shù)據(jù)。在build()方法中,我們使用ForEach循環(huán)來遍歷訂單數(shù)組,并為每個(gè)訂單創(chuàng)建一個(gè)OrderItem組件實(shí)例,傳遞相應(yīng)的屬性。
詳細(xì)解釋
-
自定義組件的定義:
OrderItem組件通過@Component裝飾器定義,使其成為一個(gè)自定義組件。它接受三個(gè)屬性:orderId、orderDate和status。 -
UI布局:在
OrderItem的build()方法中,我們使用Row布局來水平排列三個(gè)Text組件,分別顯示訂單編號(hào)、日期和狀態(tài)。每個(gè)Text組件都設(shè)置了寬度、高度、字體大小和對(duì)齊方式,以確保布局的整潔和一致性。 -
屬性傳遞:
OrderItem組件的屬性是通過@Prop裝飾器定義的,這允許父組件OrderList在創(chuàng)建OrderItem實(shí)例時(shí)傳遞這些屬性的值。 -
數(shù)據(jù)驅(qū)動(dòng):
OrderList組件的狀態(tài)變量orders包含了訂單數(shù)據(jù)。使用ForEach循環(huán),我們?yōu)槊總€(gè)訂單項(xiàng)創(chuàng)建一個(gè)OrderItem組件實(shí)例,并將訂單數(shù)據(jù)作為屬性傳遞給它。 -
重用性:
OrderItem組件是可重用的,因?yàn)樗庋b了訂單項(xiàng)的UI和邏輯,可以在OrderList頁(yè)面之外的其他部分使用,只需傳遞相應(yīng)的屬性即可。
好了,這個(gè)案例展示了如何創(chuàng)建和使用自定義組件來構(gòu)建HarmonyOS應(yīng)用的UI,以及如何通過屬性傳遞和狀態(tài)管理來實(shí)現(xiàn)數(shù)據(jù)驅(qū)動(dòng)的UI更新。關(guān)注威哥愛編程,你會(huì)發(fā)現(xiàn)他的世界里,咖啡是燃料,鍵盤是樂器,而代碼就是他的交響樂。每當(dāng)夜深人靜,別人數(shù)羊,威哥數(shù)的是代碼行數(shù)。?????????
本文來自博客園,作者:威哥愛編程,轉(zhuǎn)載請(qǐng)注明原文鏈接:http://www.rzrgm.cn/finally-vince/p/18466997

浙公網(wǎng)安備 33010602011771號(hào)