在ArkTS开发中,我们使用ForEach / if-else 来控制页面的循环布局。
ForEach
ForEach(
arr:Array, //数组
(item:any,index?:number)=>{
Row(){
...
}
},
keyGenerator?:(item: any,index?: number): string => {。 // 非常重要 大多数情况下不传
// 键生成函数 为数组每一项生成一个唯一标识,作为组件是否重新渲染的判断标准。
}
)
使用foreach 循环渲染一个商品页
这里我们构建一个类,写出一个数组来,将数组作为参数穿入下面的foreach中,完成循环渲染出一个商品列表。
class Item {
name: string
image: ResourceStr
price: number
constructor(name: string, image: ResourceStr, price: number){
this.name = name
this.image = image
this.price = price
}
}
@Entry
@Component
struct Index {
private items: Array<Item> = [
new Item('os1',$r('app.media.hongmeng'),2000),
new Item('os2',$r('app.media.hongmeng'),3000),
new Item('os3',$r('app.media.hongmeng'),4000),
new Item('os4',$r('app.media.hongmeng'),5000),
new Item('os5',$r('app.media.hongmeng'),6000)
]
build() {
Column({space:8}){
Row(){
Text('商品列表')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}
.width('100%')
.margin({bottom: 20})
// 循环控制
ForEach(
this.items,
item=>{
Row({space:10}){
Image(item.image)
.width(100)
Column({space: 4}){
Text(item.name)
.fontSize(20)
.fontWeight(FontWeight.Bold)
Text('¥' + item.price)
.fontSize(18)
.fontColor('#ff0000')
}
.height('100%')
.alignItems(HorizontalAlign.Start)
}
.width('100%')
.backgroundColor('#fff')
.borderRadius(20)
.height(120)
.padding(10)
}
)
}
.width('100%')
.height('100%')
.backgroundColor('#efefef')
.padding(20)
}
}
if-else
if(判断条件){
//内容
}else{
//内容
}
通过判断条件决定使用哪种方式渲染
通过if-else来完成折扣价格的实现
class Item {
name: string
image: ResourceStr
price: number
discount: number
constructor(name: string, image: ResourceStr, price: number,discount: number = 0){
this.name = name
this.image = image
this.price = price
this.discount = discount
}
}
@Entry
@Component
struct Index {
private items: Array<Item> = [
new Item('os1',$r('app.media.hongmeng'),2000,500),
new Item('os2',$r('app.media.hongmeng'),3000),
new Item('os3',$r('app.media.hongmeng'),4000,300),
new Item('os4',$r('app.media.hongmeng'),5000),
new Item('os5',$r('app.media.hongmeng'),6000)
]
build() {
Column({space:8}){
Row(){
Text('商品列表')
.fontSize(30)
.fontWeight(FontWeight.Bold)
}
.width('100%')
.margin({bottom: 20})
// 循环控制
ForEach(
this.items,
item=>{
Row({space:10}){
Image(item.image)
.width(100)
Column({space: 4}){
if(item.discount){
// 名字
Text(item.name)
.fontSize(20)
.fontWeight(FontWeight.Bold)
// 原价
Text('原价: ¥ ' + item.price)
.fontSize(16)
.fontColor('#ccc')
// 装饰效果
.decoration({type:TextDecorationType.LineThrough})
// 折扣价
Text('折扣价: ¥ '+(item.price - item.discount))
.fontSize(18)
.fontColor('#ff0000')
// 补贴信息
Text('补贴: ¥ ' + item.discount)
.fontSize(18)
.fontColor('#ff0000')
}else{
Text(item.name)
.fontSize(20)
.fontWeight(FontWeight.Bold)
Text('¥' + item.price)
.fontSize(18)
.fontColor('#ff0000')
}
}
.height('100%')
.alignItems(HorizontalAlign.Start)
}
.width('100%')
.backgroundColor('#fff')
.borderRadius(20)
.height(120)
.padding(10)
}
)
}
.width('100%')
.height('100%')
.backgroundColor('#efefef')
.padding(20)
}
}