
回复
你听说过 TypeScript,也听过 JavaScript,但你真的了解鸿蒙背后的“灵魂语言”ArkTS 吗?今天这篇文章带你深入掌握 ArkTS 的语法精髓,并用实战项目验证它的强大。
ArkTS = TypeScript + 鸿蒙独有语法能力
它是华为为 HarmonyOS NEXT 打造的编程语言,兼容 TypeScript 语法的同时:
对比项 | TypeScript | ArkTS |
---|---|---|
语法来源 | JS 超集 | TS 超集 |
响应式 | 需框架支持(如 Vue) | 内建响应式装饰器(@State 等) |
UI 声明 | 外部模板(如 JSX) | 纯函数式构建 UI |
编译目标 | JS | 鸿蒙ArkTS运行时 |
@Entry
@Component
struct HelloWorld {
@State text: string = '你好 ArkTS!'
build() {
Column() {
Text(this.text)
Button('点击我')
.onClick(() => {
this.text = '按钮已点击'
})
}
}
}
@Entry
:程序入口组件@Component
:定义为 UI 组件@State
:响应式状态,状态变更自动更新 UIbuild()
:类似 Vue 的模板函数,声明 UI// 父组件
@Component
struct Parent {
build() {
Child({ msg: '来自父组件的消息' })
}
}
// 子组件
@Component
struct Child {
@Prop msg: string
build() {
Text(this.msg)
}
}
@Prop
就是 props,父传子专用;支持基本类型和对象传递。
@Entry
@Component
struct TodoApp {
@State task: string = ''
@State list: Array<string> = []
build() {
Column() {
Row() {
TextInput({ placeholder: '请输入任务' })
.onChange(v => this.task = v)
Button('添加')
.onClick(() => {
if (this.task) {
this.list.push(this.task)
this.task = ''
}
})
}
ForEach(this.list, (item, index) => {
Row() {
Text(item)
Button('删除').onClick(() => this.list.splice(index, 1))
}
}, item => item)
}
}
}
ForEach
实现,和 React/Vue 不同但易懂项 | 说明 |
---|---|
类型系统 | 和 TS 一致,建议开启严格模式 |
生命周期 | @Component 支持生命周期函数(如 onAppear ) |
不支持 | 暂不支持 any , eval 等弱类型写法 |
编译器 | 使用 Ark Compiler 编译为鸿蒙原生字节码 |
《构建你的第一个鸿蒙组件化 UI 页面》——打造可复用、可组合的鸿蒙自定义组件,UI 设计师看了都说香!