1、聲明式UI語法
?
@Entry
@Component
struct My_page {@State isLogin: boolean = falsebuild() {Row() {Image(this.isLogin ? $r('app.media.icon_leon') : $r('app.media.icon')).height(60).width(60).onClick(() => {this.isLogin = !this.isLogin})Text(this.isLogin ? $r('app.string.string_to_unlogin') : $r('app.string.string_to_unlogin')).fontWeight(FontWeight.Bold).fontSize(20).fontColor(this.isLogin ? Color.Orange : Color.Black).margin({ "top": "0.00vp", "right": "0.00vp", "bottom": "0.00vp", "left": "10.00vp" })}.width('100%').margin({ "top": "20.00vp", "right": "10.00vp", "bottom": "0.00vp", "left": "10.00vp" })}
}
2、自定義組件
2.1、自定義組件生命周期
注:頁面,即由 @Entry 修飾的自定義組件
注:自定義組件,即由 @Component 修飾的UI單元
1)aboutToAppear()
2)onPageShow()
注:僅在被 @Entry 修飾的組件中生效
3)onBackPress()
注:僅在被 @Entry 修飾的組件中生效
4)onPageHide()
注:僅在被 @Entry 修飾的組件中生效
5)aboutToDisappear()
2.2、案例
注:@State 可建立起視圖與狀態之間的綁定關系
- ToItem
@Component
export default struct ToItem {public message?: string@State isComplete: boolean = false@Builder leonSelectLabel(icon: Resource) {Image(icon).objectFit(ImageFit.Contain).width('28vp').width('28vp').margin('20vp')}build() {Row() {if (this.isComplete) {this.leonSelectLabel($r('app.media.ic_ok'))} else {this.leonSelectLabel($r('app.media.ic_default'))}Text(this.message??'無').fontSize('20fp').fontWeight(FontWeight.Bold).decoration({ type: this.isComplete ? TextDecorationType.LineThrough : TextDecorationType.None }).fontColor(this.isComplete ? Color.Gray : Color.Black)}.width('100%').borderRadius(6).backgroundColor(Color.White).onClick(() => {this.isComplete = !this.isComplete})}
}
ToDoListPage
import ToDoItem from '../view/ToDoItem'
import DataModel from '../viewmodel/DataModel'@Entry
@Component
struct ToDoListPage {private todoLists: string[]aboutToAppear() {this.todoLists = DataModel.getData()}build() {Column({ space: 16 }) {Text("待辦任務列表").fontWeight(FontWeight.Bold).fontSize(30).fontColor(Color.Blue).margin({ top: 10, left: 10 })ForEach(this.todoLists, (item: string) => {ToDoItem({ message: item }).width('90%')}, (item: string) => JSON.stringify(item))}.width('100%').height('100%').backgroundColor($r('app.color.page_background'))}
}
DataModel
export class DataModel {public tasks: string[] = ["早起晨練", "準備早飯", "學習編程", "閱讀名著", "自由活動"]getData() {return this.tasks}
}export default new DataModel()