
初识ArkTS:声明式UI语法快速上手
初识ArkTS:声明式UI语法快速上手
ArkTS是鸿蒙生态的应用开发语言,基于TypeScript扩展了声明式UI能力。它通过简洁的语法结构实现高效的UI开发,具有状态驱动更新、组件化设计和响应式布局三大核心特性。
环境准备
确保已安装DevEco Studio 4.0+,创建Empty Ability模板项目。
核心语法解析
组件基础
@Component
struct WelcomePage {
build() {
// 垂直布局容器
Column() {
Text(‘Hello ArkTS!’)
.fontSize(30)
.fontWeight(FontWeight.Bold)
Button('点击触发')
.onClick(() => {
console.info('按钮被点击')
})
}
.width('100%')
.height('100%')
}
}
状态管理
@Entry
@Component
struct CounterPage {
// @State装饰器实现数据联动
@State count: number = 0
build() {
Column() {
Text(当前计数: ${this.count}
)
.margin(20)
Button('增加')
.onClick(() => {
this.count += 1 // 修改状态触发UI自动更新
})
}
}
}
样式继承
// 使用@Styles定义可复用样式
@Styles function boldText() {
.fontColor(‘#F1F1F1’)
.fontSize(18)
.fontWeight(500)
}
Text(‘统一文本样式’)
.useStyle(boldText) // 应用样式
条件渲染
@State isActive: boolean = true
build() {
Column() {
if (this.isActive) {
Text(‘状态激活’)
.backgroundColor(‘#66FF’)
} else {
Text(‘状态禁用’)
.backgroundColor(‘#AAA’)
}
Toggle({ type: ToggleType.Switch })
.onChange(value => {
this.isActive = value
})
}
}
循环渲染
@State items: string[] = [‘Ark’, ‘TS’, ‘UI’]
build() {
List() {
ForEach(this.items, (item) => {
ListItem() {
Text(item)
.padding(10)
}
})
}
}
关键特性解析
装饰器体系
@Entry:页面入口组件
@Component:可复用UI单元
@State:组件内状态管理
@Prop:父子组件单向同步
@Link:父子组件双向绑定
布局系统
线性布局:Column(纵向)、Row(横向)
弹性布局:Flex(支持wrap、justifyContent等属性)
相对定位:.position({x,y})
动态UI响应
@State positionX: number = 0
Button(‘滑动’)
.onTouch((event) => {
this.positionX = event.offsetX
})
.position({ x: this.positionX })
最佳实践
组件拆分原则
// 子组件
@Component
struct ItemCard {
@Prop content: string
build() {
Column() {
Image($r(‘app.media.icon’))
.width(40)
Text(this.content)
}
}
}
// 父组件
Column() {
ItemCard({ content: ‘卡片1’ })
ItemCard({ content: ‘卡片2’ })
}
样式复用方案
// 定义扩展方法
declare global {
interface Text {
titleStyle(): Text
}
}
Text.prototype.titleStyle = function () {
return this
.fontSize(22)
.fontColor(‘#333’)
.margin({ bottom: 10 })
}
// 使用
Text(‘标题文本’).titleStyle()
总结
ArkTS通过声明式语法解决了传统命令式UI开发的痛点:
代码简洁度提升40%+(减少DOM操作代码)
状态驱动机制降低维护复杂度
编译时检查消除90%布局错误
实际应用场景:
// 天气预报卡片组件
@Component
struct WeatherCard {
@Prop temp: number
@Prop city: string
build() {
Column() {
Text(this.city)
.titleStyle() // 复用样式
Row() {
Image($r('app.media.sun'))
.width(50)
Text(`${this.temp}℃`)
}
}
.padding(20)
.backgroundColor('#FFFFFF')
}
}
掌握ArkTS的关键是理解其"状态驱动UI"的设计哲学,通过声明组件状态与UI的绑定关系,让框架自动处理更新逻辑,使开发者能够专注于业务实现。
