最近在尝试用ArkTS应用开发语言为HarmonyOS NEXT开发一个家庭菜谱应用,记录一下实现过程中的关键点。这个应用主要功能是展示菜谱列表和详情,支持收藏功能,界面采用声明式UI开发。

数据模型与状态管理
首先定义菜谱数据模型,使用ArkTS的类与接口:
typescript

interface Ingredient {
name: string;
amount: string;
}

class Recipe {
id: number;
name: string;
difficulty: string;
ingredients: Ingredient[];
steps: string[];
isFavorite: boolean = false;

constructor(id: number, name: string, difficulty: string) {

this.id = id;
this.name = name;
this.difficulty = difficulty;

}
}

声明式UI实现
通过@Entry和@Component装饰器构建页面,使用Flex布局:
typescript

@Entry
@Component
struct RecipeListPage {
@State recipes: Recipe[] = [

new Recipe(1, "番茄炒蛋", "简单"),
new Recipe(2, "红烧排骨", "中等")

];

build() {

Column() {
  List({ space: 10 }) {
    ForEach(this.recipes, (item: Recipe) => {
      ListItem() {
        RecipeItem({ recipe: item })
      }
    })
  }
  .layoutWeight(1)
  .width('100%')
}
.height('100%')
.padding(12)

}
}

@Component
struct RecipeItem {
@Prop recipe: Recipe;

build() {

Row() {
  Image($r('app.media.food_icon'))
    .width(40)
    .height(40)
  Column() {
    Text(this.recipe.name)
      .fontSize(18)
    Text(`难度: ${this.recipe.difficulty}`)
      .fontColor('#666')
  }
  .margin({ left: 10 })
}
.width('100%')
.justifyContent(FlexAlign.Start)

}
}

交互与状态更新
通过@State和事件处理实现收藏功能:
typescript

@Component
struct RecipeDetailPage {
@State recipe: Recipe;

build() {

Column() {
  Text(this.recipe.name)
    .fontSize(22)
  Button(this.recipe.isFavorite ? '已收藏' : '收藏')
    .onClick(() => {
      this.recipe.isFavorite = !this.recipe.isFavorite;
    })
}

}
}

在HarmonyOS NEXT上开发时,ArkTS应用开发语言的静态类型检查确实能减少运行时错误,声明式UI的写法也比传统命令式更直观。不过部分API的文档还在完善中,需要多尝试不同写法。
(注:代码示例基于HarmonyOS NEXT API12版本验证,实际开发时建议参考最新官方文档)


huafushutong
1 声望0 粉丝