##Harmony OS Next ##Ark Ts ##教育本文适用于教育科普行业进行学习,有错误之处请指出我会修改。
😎 ArkTS 条件渲染超全指南 | 手把手玩转 UI 动态切换
🌟 核心能力速览
智能条件判断:用if
/else if
/else
像搭积木一样控制 UI 显示
实时响应变化:状态变量一变,UI 自动刷新超丝滑~
灵活嵌套组合:支持多层条件判断,满足复杂场景需求
版本兼容性:从 API 9 开始支持卡片开发哦!✨
🚨 使用必读规则(重点!)
// 📌 基础写法模板
if(条件1) {
// 组件1
} else if(条件2) {
// 组件2
} else {
// 默认组件
}
复制代码
🔄 更新机制揭秘
1️⃣ 条件检测 → 2️⃣ 旧组件删除 → 3️⃣ 新组件创建状态变量变动的瞬间,ArkTS 就会上演这出"三幕剧"!
🎯 实战代码教学
🔥 场景 1:数字正负判断
@Entry
@Component
struct MyComponent {
@State count: number = 0; // 🎮 核心控制变量
build() {
Column() {
Text(`当前计数:${this.count}`) // 实时显示
// 🎨 条件渲染核心区
if (this.count > 0) {
Text('正数!').fontColor(Color.Green) // 绿色提示
} else if (this.count < 0) {
Text('负数!').fontColor(Color.Red) // 红色警告
}
Button('+1').onClick(() => this.count++) // ➕按钮
Button('-1').onClick(() => this.count--) // ➖按钮
}
}
}
复制代码
💡 运行效果:点击按钮改变数值,文字颜色自动切换!
🎮 场景 2:带状态保存的计数器
@Component
struct CounterView {
@Link counter: number; // 🔗 关键链接装饰器
label: string = 'unknown';
build() {
Column({ space: 20 }) {
Text(this.label).fontSize(20)
Button(`点击+1 → ${this.counter}`)
.onClick(() => this.counter += 1)
}
.border({ width: 1 }) // 边框样式
}
}
@Entry
@Component
struct MainView {
@State toggle: boolean = true;
@State counter: number = 0; // 🏦 状态统一管理
build() {
Column() {
if (this.toggle) {
CounterView({ counter: $counter, label: '正向计数器' })
} else {
CounterView({ counter: $counter, label: '反向计数器' })
}
Button(`切换模式 ${this.toggle}`)
.onClick(() => this.toggle = !this.toggle)
}
}
}
复制代码
✨ 亮点解析:使用@Link
实现状态共享,切换模式不丢数据!
⚠️ 避坑指南
动画切换 crash 问题
错误示范:
if (this.data1) {
Text(this.data1.str) // ❌ 直接使用可能为空的数据
}
复制代码
✅ 正确姿势:方案 1:双保险判空
Text(this.data1?.str) // 🛡️ 安全访问操作符
复制代码
方案 2:禁用默认动画
Text(this.data1.str)
.transition(TransitionEffect.IDENTITY) // 🚫 禁用过渡效果
复制代码
🧠 高阶技巧
嵌套 if 的炫酷玩法:
if(外层条件){
Text("外层成立")
if(内层条件){
Text("双条件达成!").backgroundColor('#00ff00')
}
} else {
Text("外层不成立").backgroundColor('#ff0000')
}
复制代码
📌 重要提示:嵌套 if 也要遵守父容件的组件规则哦!
🎉 ArkTS ForEach 终极指南 | 花式玩转列表渲染
🌟 核心能力三连击
批量生成:像打印机一样唰唰唰生成列表项
智能复用:数据变我只变该变的部分,性能起飞🚀
动态响应:数组增删改查自动同步 UI,超贴心~
🚨 必看避坑指南
// ✅ 正确姿势:对象用唯一ID
ForEach(userList, (item) => UserCard(item), (item) => item.id)
// ❌ 作死写法:用index当key
ForEach(userList, (item) => UserCard(item), (item, index) => index)
复制代码
🔑 键值生成黑科技
ForEach(data,
item => ItemComponent(item),
item => `${item.type}_${item.timestamp}` // ✨ 自定义复合键
)
复制代码
🎯 四大实战场景
1️⃣ 静态列表(骨架屏加载)
@Entry
@Component
struct SkeletonScreen {
@State loadingData: number[] = [1,2,3,4,5]
build() {
List() {
ForEach(this.loadingData,
() => SkeletonItem(),
item => item.toString()
)
}
}
}
@Builder
function SkeletonItem() {
Row() {
Circle().width(60).height(60) // 头像占位
Column() {
Rect().width('80%').height(20) // 标题占位
Rect().width('60%').height(15) // 副标题占位
}
}.padding(10)
}
复制代码
💡 效果:加载时展示灰色块状骨架,数据到位后无缝切换真实内容
2️⃣ 动态增删(朋友圈加载更多)
@Observed
class Moment {
id: string
content: string
likes: number
constructor(id: string, content: string) {
this.id = id
this.content = content
this.likes = 0
}
}
@Entry
@Component
struct MomentsList {
@State moments: Moment[] = [
new Moment('001', '今天天气真好🌞'),
new Moment('002', '新买的球鞋到了👟')
]
loadMore() {
// 模拟加载新数据
this.moments.push(new Moment('003', '深夜放毒🍔'))
}
build() {
List() {
ForEach(this.moments,
(item) => MomentItem(item),
item => item.id
)
LoadMoreButton().onClick(() => this.loadMore())
}
}
}
复制代码
✨ 亮点:上滑自动加载,新增数据丝滑插入列表底部
3️⃣ 属性更新(点赞特效)
@Observed
class Post {
id: string
isLiked: boolean
likesCount: number
constructor(id: string) {
this.id = id
this.isLiked = false
this.likesCount = 0
}
}
@Component
struct LikeButton {
@ObjectLink post: Post
build() {
Row() {
Image(this.post.isLiked ? 'like_filled' : 'like_outline')
.onClick(() => {
this.post.isLiked = !this.post.isLiked
this.post.likesCount += this.post.isLiked ? 1 : -1
})
Text(`${this.post.likesCount}`)
}
}
}
复制代码
🔥 动效:点击爱心图标即时更新状态,数字跳动动画超带感
4️⃣ 拖拽排序(自定义列表顺序)
@Entry
@Component
struct DraggableList {
@State items: string[] = ['A', 'B', 'C', 'D']
build() {
List() {
ForEach(this.items,
(item) => {
ListItem() {
Text(item).fontSize(24)
}
.dragStart(true) // ✨ 启用拖拽
},
item => item
)
.onMove((from, to) => {
// 数据位置交换
[this.items[from], this.items[to]] = [this.items[to], this.items[from]]
})
}
}
}
复制代码
🎮 操作:长按项目自由拖动,松手后自动排序
⚠️ 血泪教训总结
Key 值雷区❗ 绝对不要用 index 当 key!会导致:
组件错误复用
状态混乱
性能急剧下降
对象更新玄机
// ❌ 错误更新方式
this.posts[0] = new Post('new') // 框架无法感知!
// ✅ 正确更新姿势
this.posts.splice(0, 1, new Post('new')) // 触发响应式更新
复制代码
动画优化技巧给动态元素添加过渡效果:
Text('重要提示')
.transition({ type: TransitionType.Insert, opacity: 0 })
.transition({ type: TransitionType.Delete, scale: 0 })
复制代码
🚀 性能优化宝典
🌈 掌握这些姿势,你就是 ArkTS 列表渲染大师!快去打造丝滑流畅的列表界面吧~
评论