发布时间:2026/7/27 10:02:01
@Component标记,并用build方法返回UI结构。typescript// 定义一个简单的文本组件@Componentstruct HelloWorld { // 状态变量,变化时会触发UI更新 @State message: string = '欢迎来到鸿蒙世界!' // build方法是组件的核心,返回UI结构 build() { Column() { Text(this.message) .fontSize(24) .fontWeight(FontWeight.Bold) .margin({ bottom: 20 }) Button('点击更新') .onClick(() => { this.message = '你点击了按钮!' }) } .padding(20) .alignItems(HorizontalAlign.Center) }}代码解析:-@Component:告诉系统这是一个UI组件-@State:标记状态变量,当其值变化时,组件会自动刷新-build():描述组件结构,类似于React中的render函数-Column:垂直布局容器,类似Flex容器-Text:文本组件,用于显示文字-Button:按钮组件,通过onClick绑定点击事件## 三、组件复用与组合:像搭积木一样构建页面实际开发中,你不会把所有代码写在一个组件里。ArkTS支持组件嵌套和复用,你可以把复杂的UI拆分成多个小组件,然后像搭积木一样组合起来。### 3.1 创建可复用的子组件typescript// 定义一个可复用的卡片组件@Componentstruct CardItem { // 通过@Prop接收父组件传递的数据 @Prop title: string @Prop description: string @Prop imageUrl: string build() { Row() { // 左侧图片 Image(this.imageUrl) .width(80) .height(80) .borderRadius(10) .margin({ right: 12 }) // 右侧文字 Column() { Text(this.title) .fontSize(18) .fontWeight(FontWeight.Medium) .lineHeight(24) Text(this.description) .fontSize(14) .fontColor('#666666') .lineHeight(20) .margin({ top: 4 }) } .alignItems(HorizontalAlign.Start) } .padding(12) .backgroundColor('#FFFFFF') .borderRadius(8) .shadow({ radius: 4, color: '#0000001A' }) .width('100%') .margin({ bottom: 8 }) }}// 在父组件中使用卡片组件@Entry@Componentstruct CardList { @State items: CardData[] = [ { title: '鸿蒙入门', desc: '学习基础组件', img: 'common/icon1.png' }, { title: '状态管理', desc: '掌握@State和@Prop', img: 'common/icon2.png' }, { title: '事件处理', desc: '交互式UI开发', img: 'common/icon3.png' } ] build() { Scroll() { Column() { // 循环渲染卡片组件 ForEach(this.items, (item: CardData, index: number) => { CardItem({ title: item.title, description: item.desc, imageUrl: item.img }) }, (item: CardData) => item.title) } .padding(16) } .backgroundColor('#F5F5F5') .height('100%') }}// 定义数据类型interface CardData { title: string desc: string img: string}代码解析:-@Prop:接收父组件传入的属性,单向数据流-ForEach:数组循环渲染,第二个参数是渲染函数,第三个参数是唯一key生成函数-Scroll:滚动容器,内容超出时自动滚动-@Entry:标记入口组件,应用启动时加载## 四、组件的生命周期与状态管理组件不是静态的,它有自己的生命周期。理解这几个阶段,能帮你写出更健壮的代码。| 生命周期方法 | 触发时机 | 常见用途 ||------------|---------|---------||aboutToAppear()| 组件即将创建时 | 初始化数据、订阅事件 ||aboutToDisappear()| 组件即将销毁时 | 清理资源、取消订阅 ||onPageShow()| 页面显示时 | 更新数据、恢复状态 ||onPageHide()| 页面隐藏时 | 暂停操作、保存数据 |typescript@Componentstruct LifecycleDemo { @State count: number = 0 private timer: number = -1 // 组件创建前触发 aboutToAppear() { console.log('组件即将创建') // 模拟定时器 this.timer = setInterval(() => { this.count++ }, 1000) as unknown as number } // 组件销毁前触发 aboutToDisappear() { console.log('组件即将销毁') // 清理定时器,防止内存泄漏 if (this.timer !== -1) { clearInterval(this.timer) } } build() { Column() { Text(`计时器:${this.count}秒`) .fontSize(20) .margin({ bottom: 20 }) Button('返回') .onClick(() => { // 模拟页面跳转,触发组件销毁 router.back() }) } .padding(30) .width('100%') .height('100%') }}## 五、组件样式与响应式设计ArkTS支持链式调用样式方法,让UI设计更直观。同时,通过@State和@Prop可以实现响应式更新。typescript@Componentstruct StyledButton { @State isPressed: boolean = false build() { Button('点击我') .width(this.isPressed ? 200 : 150) .height(50) .backgroundColor(this.isPressed ? '#007AFF' : '#4CAF50') .borderRadius(this.isPressed ? 25 : 8) .fontSize(this.isPressed ? 20 : 16) .fontColor('#FFFFFF') .shadow({ radius: this.isPressed ? 8 : 4, color: this.isPressed ? '#007AFF80' : '#4CAF5080' }) .onClick(() => { this.isPressed = !this.isPressed }) .animation({ duration: 300, // 动画时长300ms curve: Curve.EaseInOut }) }}**响应式设计技巧:**1. 使用@State标记可变状态2. 通过@Prop传递父组件数据3. 利用@Watch监听状态变化4. 使用animation方法添加过渡动画## 六、实战:构建一个简单的待办事项列表现在,结合以上知识,创建一个完整的待办事项应用:typescript@Entry@Componentstruct TodoList { @State todos: { text: string, done: boolean }[] = [ { text: '学习ArkTS组件语法', done: false }, { text: '完成实战练习', done: false } ] @State inputValue: string = '' build() { Column() { // 输入区域 Row() { TextInput({ placeholder: '输入待办事项' }) .width('70%') .height(40) .onChange((value: string) => { this.inputValue = value }) Button('添加') .width('25%') .height(40) .margin({ left: 10 }) .onClick(() => { if (this.inputValue.trim() !== '') { this.todos.push({ text: this.inputValue, done: false }) this.inputValue = '' } }) } .padding(10) .width('100%') // 待办事项列表 List() { ForEach(this.todos, (item: { text: string, done: boolean }, index: number) => { ListItem() { Row() { Checkbox() .select(item.done) .onChange((value: boolean) => { this.todos[index].done = value }) Text(item.text) .fontSize(16) .decoration({ type: item.done ? TextDecorationType.LineThrough : TextDecorationType.None }) .margin({ left: 10 }) Button('删除') .fontColor('#FF4444') .backgroundColor('transparent') .onClick(() => { this.todos.splice(index, 1) }) } .padding(10) .width('100%') } }) } .width('100%') .layoutWeight(1) } .width('100%') .height('100%') .backgroundColor('#F0F0F0') }}## 七、总结通过本文的学习,我们掌握了ArkTS组件声明的核心语法:1.基本结构:使用@Component装饰器定义组件,通过build()方法返回UI结构2.状态管理:@State管理组件内部状态,@Prop接收父组件属性3.组件组合:通过嵌套和循环渲染(ForEach)构建复杂界面4.生命周期:aboutToAppear、aboutToDisappear等钩子管理组件行为5.样式设计:链式调用样式方法,支持响应式更新和动画记住,组件声明语法的核心思想是“声明式编程”——你只需描述UI应该长什么样,框架会自动处理更新逻辑。这大大降低了UI开发的复杂度,让你能专注于业务逻辑。在实际项目中,建议将组件拆分成小而专注的单元,遵循单一职责原则。同时,善用@State和@Prop实现数据流动,配合ForEach处理列表渲染,就能轻松应对各种UI需求。下一篇文章,我们将深入讲解ArkTS的事件处理机制,包括手势识别、触摸事件等高级特性,敬请期待!