想要试试用ArkTS写出丝滑的鸿蒙软件吗?

0 阅读4分钟

ArkTS 是鸿蒙应用的开发语言。它在保持 TypeScript基本语法风格的基础上,通过规范强化静态检查和分析,提升代码健壮性。而ArkUI 是一套构建分布式应用界面的声明式 UI 开发框架,通过简洁的语法、丰富的组件、实时预览工具,提升应用界面开发效率。

以下内容假设读者有typescript和JavaScript基础。

一、数据类型

  1. 字符型:string
let a:string = 'hello'
  1. 数字型:number
let b:number = 10
  1. 布尔型:boolean
let c:boolean = true

总结:let 变量名:数据类型 = 值

使用console.log(变量名),可以打印变量。

二、数组:一次性存储多个相同类型数据

        使用:let 数组名:类型名[] = [数据1,数据2,数据3,......]

let Narray:number[] = [1,2,3,4,5]
let Sarray:string[] = ['一','one','二','two']
let Barray:boolean[]=[true,false,true,false]

数组引用:

Narray[0]
Sarray[1]
Barray[3]

三、对象:一次性存储多个不同类型数据

步骤:(1)定义接口:interface 接口名={属性名:属性数据类型,……}

            (2)使用接口定义对象:let 对象名:接口名 ={属性名:属性值,……}

interface  demo{
  name:string
  age:number
}
let info:demo ={
  name:'Bob',
  age:10
}

调用:

info.name
info.age

如果调用整个对象,只会显示对象类型,不会显示值

四、函数:封装重复性代码提高效率

步骤(1)定义函数:function 函数名(形式参数列表) {函数体}

形式参数列表形式:形式参数1:数据类型,形式参数2:数据类型……

函数可以没有形式参数

函数体可以没有返回值

        (2)使用函数:函数名(实际参数列表)

定义示例:

function addNumber(first:number,second:number){
  return first+second
}

调用示例:

addNumber(1,2)

没有形式参数和返回值的函数:

function printInfo(){
  console.log('日志打印')
}
printInfo()

箭头函数形式:let 函数名 = (形式参数列表)=> {函数体}

let addNumber2 = (first:number,second:number) => { 
  return first + second 
}
console.log(addNumber2(1, 2).toString())

五、组件

分类容器组件内容组件
使用组件名(){}组件名()
示例Column(){}//纵向排列组件
Row(){}//横向排列组件
Text('内容')
@Entry
@Component
struct Index {

  //build里面要有唯一容器根组件
  build() {
      Column(){
        Text('一')
        Text('二')
        Text('三')
      }
  }
}

2026-01-28-17-48-38-image.png

@Entry
@Component
struct Index {

  //build里面要有唯一容器根组件
  build() {
      Row(){
        Text('一')
        Text('二')
        Text('三')
      }
  }
}

2026-01-28-17-49-49-image.png

@Entry
@Component
struct Index {

  build() {
    Column(){
      Column(){
        Text('一')
        Text('二')
        Text('三')
      }
      Row(){
        Text('一')
        Text('二')
        Text('三')
      }
    }
  }
}

2026-01-28-17-50-46-image.png

build里面的容器根组件唯一

(一)图像组件

Image(文件路径)

本地:$r('app.media.文件名')

本地图片实际对应应放在entry\src\main\resources\base\media

网络:http://xxx.xxx

示例代码:

@Entry
@Component
struct Index {

  build() {
    Column(){
      Image($r('app.media.test'))
        .width(300)
      Image('https://www.huawei.com/-/media/hcomponent-header/1.0.1.20251208095539/component/img/huawei_logo.png')
        .width(200)
    }
  }
}

2026-01-29-16-16-11-image.png

(二)列表组件

示例代码:

@Entry
@Component
struct Index {
  build() {
    Column() {
      Text('猜你喜欢')
        .fontColor(Color.White)
        .width('100%')
        .margin({ bottom: 10 })
      List() {
        ListItem() {
          Row() {
            //图片
            Image('http://p2.music.126.net/CDhYcShQKH2VAMENuCxWWQ==/109951164166513349.jpg?param=130y130')
              .width(80)
              .border({radius:8})
              .margin({right:10})
            //文字
            Column(){
              Text('悬溺')
                .fontColor('#f3f3f3')
                .width('100%')
                .fontWeight(700)
                .margin({bottom:15})
              Row(){
                Text('VIP')
                  .fontColor('#9a8e28')
                  .border({width:1,color:'#9a8e28',radius:12})
                  .padding({left:5,right:5,top:3,bottom:3})
                  .margin({right:10})
                Text('葛东琪')
                  .fontColor('#696969')
              }
              .width('100%')//左对齐
            }
            .layoutWeight(1)//占用剩下所有空间
            //更多
            Image($r('app.media.ic_more'))
              .width(24)
              .fillColor(Color.White)//svg填充颜色
          }
          .width('100%')
          .height(80)
          //.backgroundColor(Color.Pink)
          .margin({ bottom: 10 })
        }
      }.scrollBar(BarState.Off)//滚动条状态(自动、开、关)
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#131313')
    .padding({ left: 10, right: 10 })
    .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM]) //扩充组件安全区域
  }
}

使用List(){}包含组件形成一个列表,每一条用ListItem(){}实现,例如:

List() {
        ListItem() {
        //详细内容
        }
}

使用.listDirection可以控制方向

(三)层叠布局组件

使用方法:

Stack(){
    组件1
    组件2
}

把要叠加的组件放在{}里面,即可叠加在一起

使用Stack({ alignContent: Alignment. TopEnd })可以设置组件层叠对齐方式

(四)Tab组件

使用方法:

Tabs({barPosition: BarPosition. 对齐位置}) {
    TabContent(){
        // 内容
    }
    .tabBar() //菜单
}

示例代码:

@Entry
@Component
struct Index {
  build() {
    Tabs({ barPosition: BarPosition.End }) {
      ForEach([1, 2, 3, 4], (index: number) => {
        TabContent() {
          Text('内容' + index)
        }
        .tabBar('菜单' + index)
      })
    }
  }
}

结果:

2026-02-04-10-17-56-image.png

可以使用onChange控制点击的变化

(五)输入框组件

使用方法:

TextInput({ placeholder:'提示信息'})
·placeholderColor(‘提示信息色值’)

示例代码:

@Entry
@Component
struct Index {
  build() {
    Column(){
      TextInput({placeholder:'请输入……'})
        .placeholderColor(Color.Brown)
    }
    .padding(10)
  }
}

结果:

2026-02-04-10-54-04-image.png

(六)轮播图组件

使用方法:

Swiper() {
    // 内容
}
.autoPlay(true)//自动播放

内容可以使用ForEach循环渲染

六、属性

使用方法:组件.属性(值)

(一) 通用属性

常用通用属性:

属性名作用属性值注意事项
width宽度(左对齐)数值(vp)最大:360或100%
height高度数值(vp)最大:360或100%
backgroundColor背景色内置颜色或十六进制值

示例:

@Entry
@Component
struct Index {

  //build里面要有唯一容器根组件
  build() {
    Column(){
      Text('文本')
        .backgroundColor(Color.Orange)
        .width(100)
        .height(50)
      Row(){}
        .width(300)//满屏360
        .height(100)
        .backgroundColor('#ff6600')
    }
  }
}

2026-01-29-15-03-40-image.png

(二)文本属性

常用:

属性名作用属性值
fontSize字体大小数值(fp)
fontColor字体颜色内置颜色或十六进制值
fontWeight字体粗细100~900(默认400)
MaxLines最大行数数值
textOverFlow移除显示多种,根据实际选择

示例:

@Entry
@Component
struct Index {

  build() {
    Column(){
      Text('测试组件')
        .fontSize(30)
        .fontColor(Color.Red)
        .fontWeight(800)
    }
  }
}

2026-01-29-15-08-41-image.png

## (三)边距属性

外边距:margin 内边距 :padding

  1. 四个方向相同:
组件
    ·padding(数值)
    ·margin(数值)
  1. 四个方向不同:
组件
   .padding({top: 值, bottom: 值, left: 值, right: 值})
   .margin({top: 值, bottom: 值, left: 值, right: 值})

原始代码:

@Entry
@Component
struct Index {
  build() {
    Column() {
      Button('登录')
        .width('100%')
      Button('注册')
        .width('100%')
        .backgroundColor(Color.Gray)
    }
    .backgroundColor('#DDDDDD')

  }
}

结果:

2026-01-31-10-01-32-image.png

加入内边距,和边缘分离:

@Entry
@Component
struct Index {
  build() {
    Column() {
      Button('登录')
        .width('100%')
      Button('注册')
        .width('100%')
        .backgroundColor(Color.Gray)
    }
    .backgroundColor('#DDDDDD')
    .padding({
      left: 10,
      top: 20,
      right: 30,
      bottom: 40
    })
  }
}

结果:

2026-01-31-10-02-50-image.png

加入外边距分离两个按钮:

@Entry
@Component
struct Index {
  build() {
    Column() {
      Button('登录')
        .width('100%')
        .margin({ bottom: 20 })
      Button('注册')
        .width('100%')
        .backgroundColor(Color.Gray)
    }
    .backgroundColor('#DDDDDD')
    .padding({
      left: 10,
      top: 20,
      right: 30,
      bottom: 40
    })
  }
}

结果:

2026-01-31-10-05-34-image.png

(四)边框属性

组件
    .border({width:粗细,color:颜色,style:线条样式,radius:圆角})

示例代码:

@Entry
@Component
struct Index {
  build() {
    Column() {
      Text('点赞')
        .width(100)
        .height(60)
        .backgroundColor(Color.Pink)
        .textAlign(TextAlign.Center)
        .border({
          width: 2,
          color: Color.Blue,
          style: BorderStyle.Dotted,
          radius: 30
        })
    }
    .padding(20)
  }
}

效果:

2026-01-31-10-16-01-image.png

使用.clip(true)来裁剪内部以贴合外组件边框

(五)安全区域属性

.expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])

可以将安全区域从两边留白扩展到整个屏幕

TOP设置扩展到顶部(通知栏)

BOTTOM设置扩展到底部(任务栏)

(六)滚动条属性

.scrollBar(BarState.Off)

可以设置On、Off、Auto,控制滚动条的显示与否

(七)扩展填充属性

.layoutWeight(1)

设置1即扩展填充剩余所有的空间,0则不填充

(八)颜色填充属性

.fillColor(Color.White)

可以修改图片填充颜色,最好是svg格式的,一般用于Image组件

七、结构语句

(一)if分支语句

使用方法:

if (条件1) {
  //条件1满足时执行代码
} else if (条件2) {
  //条件1不满足执行代码,条件2满足时执行代码
} else {
  //条件均满足时执行代码
}

示例代码:

let score: number = 58
if (score >= 80) {
  console.log('等级:A')
} else if (score >= 70) {
  console.log('等级:B')
} else if (score >= 60) {
  console.log('等级:C')
} else {
  console.log('不及格!')
}

在实际项目中,可用于条件渲染,根据需要显示不同内容

let num: number = 20

@Entry
@Component
struct Index {
  build() {
    Column() {
      if (1 === num) {
        Text('文本1')
      } else if (2 === num) {
        Text('文本2')
      } else {
        Text('无文本')
      }
    }
  }
}

(二)条件表达式语句

条件?条件成立的表达式:条件不成立的表达式

示例代码:

let num1: number = 10
let num2: number = 20
let result: number = num1 > num2 ? num1 : num2
console.log('最大值是', result);

可用于条件渲染

(三)循环渲染语句

ForEach(数组,(item:类型,index: number) => {
    组件
})

示例代码:

let name: string[] = ['张三', '李四', '王五']

@Entry
@Component
struct Index {
  build() {
    Column() {
      ForEach(name, (item: string, index: number) => {
        Text(item + index)
      })
    }
    .padding(20)
  }
}

结果:

2026-02-02-11-05-45-image.png

八、状态管理和事件处理

应用的运行时的状态是参数,当参数改变时,UI渲染刷新

状态变量:使用装饰器装饰,状态变量数据改变会引起UI的渲染刷新

使用V2版本管理:

@ComponentV2
struct xxx {
  @Local 变量

注意:

  1. 状态必须设置数据类型
  2. 状态必须设置初始值

使用this关键字修改

示例代码:

let name: string[] = ['张三', '李四', '王五']

@Entry
@ComponentV2
struct Index {
  @Local num: number = 1

  build() {
    Column() {
      Row() {
        Text('-')
          .width(40)
          .height(40)
          .border({ width: 1, color: '#999', radius: { topLeft: 3, bottomLeft: 3 } })
          .textAlign(TextAlign.Center)
          .onClick(() => {
            if (this.num > 1) {
              this.num--
            }
          })
        Text(this.num.toString())
          .width(40)
          .height(40)
          .border({ width: { top: 1, bottom: 1 }, color: '#999' })
          .textAlign(TextAlign.Center)
          .fontSize(18)
        Text('+')
          .width(40)
          .height(40)
          .border({ width: 1, color: '#999', radius: { topRight: 3, bottomRight: 3 } })
          .textAlign(TextAlign.Center)
          .onClick(() => {
            this.num++
          })
      }
      .padding(50)
    }
    .padding(20)
  }
}

结果:

2026-02-03-11-37-04-20260203-0336-54.8126786.gif

  1. onClick定义点击执行的代码块

九、使用@Builder装饰函数控制UI

使用@Builder 装饰函数,封装的UI元素,提升复用性,@Builder装饰的函数也称为“自定义构建函数”。

定义:

@Builder
自定义构建函数名(参数列表){
要复用的组件结构
}

使用:

this.自定义构建函数名(数据列表)

示例代码:

let name: string[] = ['张三', '李四', '王五']

@Entry
@ComponentV2
struct Index {
  @Builder
  titleBuilder(title: string) {
    Row() {
      Text(title)
        .fontColor('#fff')
        .fontWeight(700)
        .layoutWeight(1)
      Image($r('app.media.ic_more'))
        .width(22)
        .fillColor('#fff')
    }
    .width('100%')
    .height(50)
  }

  build() {
    Column() {
      this.titleBuilder('标题1')
      this.titleBuilder('标题2')
    }
    .width('100%')
    .height('100%')
    .backgroundColor('#131313')
    .padding({ left: 10, right: 10 })
  }
}

结果:

2026-02-03-11-52-52-image.png

十、项目开发

(一)图标设置

配置文件:项目目录\entry\src\main\module.json5

具体位置:

{
  "module": {
    ……
    "abilities": [
      {
        ……
        "icon": "$media:layered_image",//软件显示图标
        "label": "$string:EntryAbility_label",//软件显示名称
        "startWindowIcon": "$media:startIcon",//启动图标
        "startWindowBackground": "$color:start_window_background",//启动背景
        ……
      }
    ],
    ……
  }
}

图片资源在项目名称\entry\src\main\resources\base\media\文件名

文本资源在项目名称\entry\src\main\resources\base\element\string.json

(二)跳转设计

Navigation组件Navigation-导航与切换-华为HarmonyOS开发者

(三)生命周期函数

生命周期函数是组件中自动执行的函数,需要写在build(){}之前。

  1. ababoutToAppear(): void { 函数体 },例如下面这个延时执行:
aboutToAppear(): void {
  setTimeout(()=>{
    //要执行的内容
  },等待时间(毫秒))
}

(四)项目文件交互

  1. 使用explort 关键字导出组件、函数

  2. 使用import 关键字导入组件、函数

(五)软件权限

module.json5中设置权限:声明权限-华为HarmonyOS开发者

(六)多页面跳转存储UI状态、全局共享数据

AppStorageV2: 应用全局UI状态存储-管理应用拥有的状态

使用:

AppStorageV2.connect(类型,key,初始值构造器);

(七)启动准备

项目名称\entry\src\main\ets\entryability\EntryAbility.ets的下面代码内设置:

……
onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    //写在这下面
    ……
  }
……