鸿蒙列表渲染,封装内容组件,进行item传参会报错?
class FoodClass {order_id: number = 0food_name: string = ""food_price: number = 0food_count: number = 0
}@Entry
@Component
struct Demo07 {@State message: string = 'Hello World'@State cartList: FoodClass[] = [{order_id: 1,food_name: '鱼香肉丝',food_price: 18.8,food_count: 1},{order_id: 2,food_name: '粗溜丸子',food_price: 26,food_count: 2},{order_id: 3,food_name: '杂粮煎饼',food_price: 12,food_count: 1}]build() {Row() {Column({space:20}) {ForEach(this.cartList,(item:FoodClass)=>{FoodItem({ item: $item })})}.width('100%')}.height('100%')}
}@Component
struct FoodItem {@link item:FoodClassbuild() {Row(){Text(this.item.food_name)Text(`价格:${this.item.food_price}`)Text(`数量:${this.item.food_count}`)}.width('100%').justifyContent(FlexAlign.SpaceAround)}
}
报错:
ArtTS不支持这么做,也就是Link修饰的数据必须得是最外层的 State数据,想要实现我们刚刚的设想,我们还得另辟蹊径。-后续ObjectLink 和Observerd会解决这个问题
解决方案:需要使用arkts官方提供的@ObjectLink 和@Observerd 以及 next版本规范的定义对象的interface解决
当然,如果只是对item内容进行纯ui渲染, 可以不使用装饰器修饰,直接进行数据传递和接受渲染即可
import { goodsModel } from './Demo05'
@Entry
@Component
struct Demo07 {@State message: string = 'Hello World'@State cartList: FoodClass[] = [new FoodClassModel({order_id: 1,food_name: '鱼香肉丝',food_price: 18.8,food_count: 1}), new FoodClassModel({order_id: 2,food_name: '粗溜丸子',food_price: 26,food_count: 2}), new FoodClassModel({order_id: 3,food_name: '杂粮煎饼',food_price: 12,food_count: 1})]show(){return this.cartList.reduce((n,m)=>{return n+m.food_count},0)}build() {Row() {Column({ space: 20 }) {ForEach(this.cartList, (item: FoodClassModel) => {FoodItem({ item:item,carList:$cartList })})Text(this.show()+'')}.width('100%')}.height('100%')}
}@Component
struct FoodItem {@ObjectLink item: FoodClassModel@Link carList:FoodClassModel[]build() {Row() {Text(this.item.food_name)Text(`价格:${this.item.food_price}`)Text(`数量:${this.item.food_count}`).onClick(()=>{this.carList = this.carList.map((aa:FoodClassModel)=>{if(aa.order_id===this.item.order_id){aa.food_count++}return aa})})}.width('100%').justifyContent(FlexAlign.SpaceAround)}
}interface FoodClass {order_id: numberfood_name: stringfood_price: numberfood_count: number
}@Observed
export class FoodClassModel implements FoodClass {order_id: number = 0food_name: string = ''food_price: number = 0food_count: number = 0constructor(model: FoodClass) {this.order_id = model.order_idthis.food_name = model.food_namethis.food_price = model.food_pricethis.food_count = model.food_count}
}
案例中:父组件的总和,是需要再传一个list数据进去,在子组件中使用@link 进行数据双向更新,才能实现ui试图更新的,因为鸿蒙数据只支持单层数据响应式更新。
鸿蒙-传智播客-博学谷