一、ForEach
语法:
private items = [
{
name:"admin",
address:"郑州"
},
{
name:"user",
address:"云南"
},
{
name:"super",
address:"江西"
}
]
ForEach(
array:Array, // 要遍历的数据数组
(item:any,index?:number)=>{ // 遍历
},
// 键生成函数,为数组每一项生成一个唯一标识,组件是否重新渲染的判断标准
// 类似于Vue中for循环的key,这里不需要定义key,默认有值
keyGenerator?:(item:any,index?:number):string=>{
}
)
class Shop{
name:string
img:ResourceStr
price:number
constructor(name:string,img:ResourceStr,price:number) {
this.name = name
this.img = img
this.price = price
}
}
@Entry
@Component
struct ForEachUI {
private shops:Array<Shop> = [
new Shop("华为mate70旗舰手机",$r("app.media.down"),8999),
new Shop("华为mate70旗舰手机",$r("app.media.down"),9999),
new Shop("华为mate70旗舰手机",$r("app.media.down"),10999)
]
build() {
Column(){
Row(){
Text("商品列表")
.fontSize(30)
}
.width("90%")
.height("60")
ForEach(this.shops,(item:Shop) =>{
Row(){
Image(item.img)
.width(100)
Column(){
Text(item.name)
.fontWeight(FontWeight.Bold)
Text("¥"+item.price)
.fontColor("red")
}
.alignItems(HorizontalAlign.Start)
}
.width("90%")
.backgroundColor("#ffffff")
.height("15%")
.borderRadius(8)
.margin({bottom:10})
})
}
.width("100%")
.height("100%")
.backgroundColor("#c7c7c7")
}
}
二、if-else
语法:
// 在TS中,如果获取的值为0,那么条件结果为false,否则为true
if(0:1){
}else{
}
三、需求
class Shop{
name:string
img:ResourceStr
price:number
status:number
constructor(name:string,img:ResourceStr,price:number,status:number) {
this.name = name
this.img = img
this.price = price
this.status = status
}
}
@Entry
@Component
struct ForEachUI {
private shops:Array<Shop> = [
new Shop("华为mate70旗舰手机",$r("app.media.down"),8999,500),
new Shop("华为mate70旗舰手机",$r("app.media.down"),9999,200),
new Shop("华为mate70旗舰手机",$r("app.media.down"),10999,0)
]
build() {
Column(){
Row(){
Text("商品列表")
.fontSize(30)
}
.width("90%")
.height("60")
ForEach(this.shops,(item:Shop) =>{
Row(){
Image(item.img)
.width(100)
Column({space:4}){
if (item.status) {
Text(item.name)
.fontWeight(FontWeight.Bold)
Text("原价:¥"+item.price)
.fontColor("#c7c7c7")
.decoration({type:TextDecorationType.LineThrough})
.fontSize(14)
Text("折扣价:¥"+(item.price - item.status))
.fontColor("red")
Text("补贴:¥"+item.status)
.fontColor("red")
} else{
Text(item.name)
.fontWeight(FontWeight.Bold)
Text("¥"+item.price)
.fontColor("red")
}
}
.alignItems(HorizontalAlign.Start)
}
.width("90%")
.backgroundColor("#ffffff")
.height("15%")
.borderRadius(8)
.margin({bottom:10})
})
}
.width("100%")
.height("100%")
.backgroundColor("#c7c7c7")
}
}
eight("15%")
.borderRadius(8)
.margin({bottom:10})
})
}
.width("100%")
.height("100%")
.backgroundColor("#c7c7c7")
}
}