第 6 节:ArkUI 声明式范式与核心组件
学习目标
- 理解声明式 UI 和命令式 UI 的根本差别,建立「状态是唯一真相源」的思维。
- 写合法的
build():单根容器、条件渲染、列表渲染。 - 熟练使用 Text / Image / Button / TextInput 四个基础组件及其通用属性、事件。
- 用
@Param/@Event抽出可复用的自定义组件。
一、引入:你描述「界面该长什么样」,框架负责刷新
写界面有两种思路。命令式:你像写操作流程一样,先拿到按钮对象,再调它的方法改文字、绑事件,每一步都亲手指挥。声明式:你不直接碰控件对象,而是写一段「配置」——在这个状态下这里显示文字、这里是蓝色按钮;状态变了,框架根据配置重新算出新界面并做最小化更新。
// 命令式思路(伪代码,仅作对比):你要亲手管理控件和每一次变更
// Button btn = findViewById(R.id.submit);
// btn.setText("提交");
// btn.setOnClickListener(v -> { btn.setText("已提交"); btn.setEnabled(false); });
// 声明式思路(ArkTS):只描述「状态 count 决定界面长什么样」
Button(count === 0 ? '提交' : '已提交')
.enabled(count === 0)
.onClick(() => count++);
差别在于:命令式里「界面」是被你反复修改的对象,状态一多就要在各回调里手写「现在显示哪个」,很容易漏更新。声明式里界面是状态的纯函数:同一个状态一定渲染出同一个界面,你只改状态,框架自动重算。
二、核心概念与正文
2.1 @Entry / @ComponentV2 与 build()
一个 .ets 文件就是若干个用 struct 描述的自定义组件:
@Entry:标记页面根组件,一个页面文件只能有一个;@ComponentV2:标记可复用自定义组件(V2 状态写法,新代码默认全用它)。
每个组件必须实现 build(),返回组件树。ArkUI 对 build 里能写什么有严格约束:
- 有且仅有一个根容器:多个组件并列时必须用 Column/Row/Stack 包起来;
- 条件渲染用
if/else,列表用ForEach,它们必须放在容器内部; - build 要「纯」:不要在里面发网络请求、做排序过滤,计算好的数据再传进来;
- 容器组件用
{}包子内容,普通组件不用;属性方法点开头、括号闭合、不加分号。
@Entry
@ComponentV2
struct BuildRules {
@Local loading: boolean = true;
@Local names: string[] = ['苹果', '香蕉'];
build() {
Column() {
// 条件渲染:if 放在容器内部,合法
if (this.loading) {
Text('加载中...')
} else {
// 列表渲染:ForEach 生成多个 Text
ForEach(this.names, (item: string) => {
Text(item)
})
}
}
.width('100%')
}
}
// ❌ 反例:build() 直接有 Text 和 Button 两个根节点,编译报错
// struct Bad {
// build() {
// Text('a')
// Button('b')
// }
// }
自定义组件的生命周期钩子先混个脸熟:aboutToAppear()(build 前,初始化数据)、aboutToDisappear()(销毁前,释放资源)。
2.2 四个基础组件
Text:显示文字,常用 fontSize/fontColor/fontWeight/lineHeight/maxLines/textOverflow:
Column({
space: 8 }) {
Text('静夜思')
.fontSize(24)
.fontWeight(FontWeight.Bold)
.fontColor('#111')
Text('床前明月光,疑是地上霜。举头望明月,低头思故乡。')
.fontSize(14)
.fontColor('#666')
.maxLines(2)
.textOverflow({
overflow: TextOverflow.Ellipsis }) // 超出省略号
}
.width('100%').padding(16)
Image:支持本地资源 $r('app.media.xxx') 和网络图片(网络图需申请 ohos.permission.INTERNET):
Column({
space: 12 }) {
Image($r('app.media.icon'))
.width(80).height(80)
.borderRadius(40) // 圆形头像
.objectFit(ImageFit.Cover)
Image('https://example.com/cover.png')
.width('100%').height(160)
.borderRadius(12)
.alt($r('app.media.placeholder')) // 加载中占位图
}
Button:{ type: ButtonType.Capsule } 决定形状:
Button('提交', {
type: ButtonType.Capsule })
.width('100%').height(48)
.backgroundColor('#0A59F7')
.fontColor(Color.White)
.onClick(() => {
/* 提交逻辑 */ })
TextInput:用 { text: $变量, placeholder } 做受控输入,和 @Local 天然双向同步:
@Entry
@ComponentV2
struct TextInputDemo {
@Local username: string = '';
build() {
Column({
space: 12 }) {
TextInput({
text: $username, placeholder: '请输入用户名' })
.height(48).width('100%')
.borderRadius(8)
.backgroundColor('#F5F6F8')
Text(`你输入的是:${
this.username}`).fontColor('#666')
}
.width('100%').padding(16)
}
}
$username 这种 $ 引用是 V2 的双向绑定语法糖,框架会自动把输入框内容回写到 username。密码框用 .type(InputType.Password),数字键盘用 .type(InputType.Number)。
2.3 通用属性与通用事件
所有内置组件都支持一套通用属性(尺寸、边距、背景、边框、可见性)和事件:
Column({
space: 16 }) {
Column() {
Text('我是一张卡片')
}
.width(220).height(120)
.padding(16) // 内边距
.margin({
top: 8, bottom: 8 }) // 外边距
.backgroundColor('#F1F3F5')
.border({
width: 1, color: '#DDD', radius: 12 })
.onClick(() => {
/* 点击 */ })
Button('切换显示')
.onClick(() => {
this.visible = !this.visible; })
}
几个易混语义:
| API | 作用 | 常见取值 |
|---|---|---|
.padding |
内容与边框之间 | number 或 { left/right/top/bottom } |
.margin |
组件与外部之间 | 同上 |
.borderRadius |
圆角 | number;等于宽度一半变圆 |
.visibility |
可见性 | Visible / Hidden(占位)/ None(不占位) |
事件侧常用:.onAppear()(挂载时发首屏请求)、.onDisAppear()(移除时清理)、.onTouch()(TouchType.Down/Up/Move)。颜色有 '#RRGGBB'、'#AARRGGBB'、Color.Red 三种写法;尺寸单位默认是 vp(虚拟像素,随密度自动缩放)。
2.4 组件复用:@Param / @Event
把重复出现的界面抽成自定义组件,是可维护性的关键。V2 里父子通信走 @Param(父传子,输入)和 @Event(子通过回调通知父,输出):
@ComponentV2
struct CounterCard {
@Param title: string = ''; // 从父传入
@Param initial: number = 0;
@Event onCountChange: (value: number) => void = () => {
}; // 输出回调
@Local count: number = 0;
aboutToAppear(): void {
this.count = this.initial;
}
build() {
Column({
space: 10 }) {
Text(this.title).fontSize(16).fontColor('#333')
Row({
space: 16 }) {
Button('-1').width(56).onClick(() => {
this.count--;
this.onCountChange(this.count); // 把最新值抛给父
})
Text(`${
this.count}`).fontSize(22).textAlign(TextAlign.Center)
Button('+1').width(56).onClick(() => {
this.count++;
this.onCountChange(this.count);
})
}
}
.padding(16).backgroundColor('#F5F6F8').borderRadius(12).width('100%')
}
}
@Entry
@ComponentV2
struct Index {
@Local total: number = 0;
build() {
Column({
space: 16 }) {
CounterCard({
title: '阅读时长(分钟)',
initial: 0,
onCountChange: (v: number) => {
this.total = v; }
})
Text(`当前累计:${
this.total} 分钟`).fontColor('#0A59F7')
}
.width('100%').padding(16)
}
}
卡片本身不知道「累计」要做什么,只负责把数字变化抛出去——父组件决定怎么处理。这就是组件与业务解耦。注意 @Param 对对象、数组是引用语义,子组件改它的属性会影响父组件那份数据,要隔离就先深拷贝。
三、完整示例:一个可复用的输入框卡片
把 TextInput + 通用属性 + 自定义组件组合成一个真实表单单元:
@ComponentV2
struct LabeledInput {
@Param label: string = '';
@Param hint: string = '';
@Event onChange: (value: string) => void = () => {
};
build() {
Column({
space: 6 }) {
Text(this.label).fontSize(13).fontColor('#666')
TextInput({
placeholder: this.hint })
.height(44).width('100%')
.backgroundColor('#F5F6F8')
.borderRadius(8)
.onChange((value: string) => this.onChange(value))
}
.width('100%')
}
}
@Entry
@ComponentV2
struct LoginPage {
@Local account: string = '';
@Local password: string = '';
build() {
Column({
space: 16 }) {
LabeledInput({
label: '账号', hint: '请输入手机号',
onChange: (v: string) => {
this.account = v; }
})
LabeledInput({
label: '密码', hint: '请输入密码',
onChange: (v: string) => {
this.password = v; }
})
Button(`登录(账号长度 ${
this.account.length})`)
.width('100%').height(48)
.onClick(() => {
/* 登录逻辑 */ })
}
.width('100%').height('100%').padding(20)
.justifyContent(FlexAlign.Center)
}
}
运行效果:两个带标签的输入框,下面一个按钮实时显示账号长度。LabeledInput 可以在任何表单里复用。
四、踩坑提示
⚠️ 坑 1:build() 两个根节点没套容器。 编译报 "build should have one root",多了就用 Column/Stack 包。
⚠️ 坑 2:网络图加载不出来。 先在 module.json5 申请
ohos.permission.INTERNET,并配置 cleartext/域名白名单;开发时先用.alt()占位图别黑屏。⚠️ 坑 3:Visibility.Hidden 以为是不占位。 Hidden 只是看不见、仍占布局;要真正从布局移除用
Visibility.None,或直接用if。⚠️ 坑 4:在子组件里改 @Param 对象导致父组件数据被改。 @Param 是引用语义,要隔离先深拷贝到 @Local。
五、小结
- 声明式 UI:界面是状态的纯函数,你只改状态,框架自动 diff 刷新,永远不要找「那个控件对象」。
- build() 单根容器、条件用
if、列表用ForEach、保持纯函数。 - 四组件:Text 文字、Image 图片、Button 按钮、TextInput 输入;尺寸单位是 vp。
- 抽组件用
@Param(入)+@Event(出),数据流单向显式。
六、思考题 / 实践任务
- 动手任务:把上面的登录页加一个「显示密码」开关(用
@Local showPwd: boolean),切换密码框的type在Password和Normal之间。 - 动手任务:抽一个
SectionCard组件,接收@Param title,内部用通用属性画出带圆角、内边距的卡片容器。 - 思考题:为什么说「build 里不要发请求、不要做排序」?如果在 build 里改 @Local 会发生什么?
组件会用了,但怎么排版?一行三个标签均分、图片上盖标题、标签自动换行——下一节讲 Row/Column/Stack/Flex 这几个最常用的布局容器,让你能拼出任意页面结构。