效果录屏
鸿蒙循环渲染
概要
提示:使用鸿蒙List组件进行ForEach循环渲染页面数据(数组对象),并触底加载分页;
注意的点
提示:
ForEach循环数组对象时,要指定对象的唯一标识,例如 index下标(便于设置单独单击事件或者判断样式);
(分享代码,仅供参考)
1. 接口返回数据
// 导入ts页面axios请求接口
import feedbackListModule from '../../../../pageModules/feedbackListModule'
// 鸿蒙自带API弹窗组件
import promptAction from '@ohos.promptAction'
@Entry
@Component
struct feedbackRecording {
// 后台返回的数据类型,数组中包含多个对象(数据是随便找的)
// [
// { type: '砍价活动', content: '砍价活动', images : 'https://88888.png,https://88888.png' },
// { type: '拼团活动', content: '砍价活动', images : 'https://88888.png,https://88888.png' },
// { type: '限时秒杀', content: '砍价活动', images : 'https://88888.png,https://88888.png' },
// { type: '热销榜单', content: '砍价活动', images : 'https://88888.png,https://88888.png' },
// ]
@State list: object[] = [];
// 页面刷新
onPageShow() {
this.loadFeedbackList();
}
// 加载数据
loadFeedbackList() {
// 调用组件内的接口函数
feedbackListModule.reqList()
.then(res => {
res.data.list.data.forEach(element => {
if (element.images != null) {
element.imgList = element.images.split(",");
} else {
element.images = ""
}
this.list.push(element)
})
this.list = this.list.concat(res.data.list.data);
feedbackListModule.last_page = res.data.list.last_page;
// console.log("数据返回---" + JSON.stringify(res.data.list.data))
console.log("数据返回---" + this.list)
})
}
}
2. List循环部分
List({ space: 10 }) {
ForEach(this.list, (item, index) => {
ListItem() {
Column({ space: 4 }) {
Row() {
Text('文本标题:' + item.type)
Text(item.createtime)
.fontSize(14)
.fontColor('#ff969696')
}.width('100%').justifyContent(FlexAlign.SpaceBetween)
Text('文本标题:' + item.content)
.fontSize(15)
.fontColor('#ff969696')
Flex() {
ForEach(item.imgList, (item, index) => {
Image(item)
.width(66).height(66).margin({ right: 10 })
})
}
}
.alignItems(HorizontalAlign.Start)
.width('100%')
.height(150)
.backgroundColor('#fff')
.borderRadius(2)
.padding(10)
}
})
}
// 触底加载
.onReachEnd(() => {
if (feedbackListModule.current_page > feedbackListModule.last_page) {
promptAction.showToast({ message: '暂无更多...' });
return;
}else{
feedbackListModule.current_page++;
this.loadFeedbackList();
}
})
最近也是刚自学鸿蒙,还是建议新学者多参考和学习前辈已写好的项目,从中可以学习很多新的写法,解决很多不解的问题,边学边实战。