鸿蒙开发-Link使用

2024-05-20  本文已影响0人  激扬飞雪
@Entry
@Component
struct PropCase {
  @State num: number = 0
  build() {
    Row() {
      Column({space: 10}) {
        Text(this.num.toString())
          .fontSize(30)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            this.num++
          })
       Divider()
         .color(Color.Green)
         .strokeWidth(10)
        Child({num: $num})
      }
      .width('100%')
    }
    .height('100%')
  }
}

@Component
struct Child {
  @Link num: number;
  build() {
    Text(this.num.toString())
      .fontSize(30)
      .fontWeight(FontWeight.Bold)
      .onClick(() => {
        this.num++
      })
  }
}
image.png
@Entry
@Component
struct LinkCase {
  @State message: string = 'Hello World'
  @State foodList: Food[] = [
    {
      id: 1,
      name: '鱼香肉丝',
      price: 18.2,
      num: 10
    },
    {
      id: 2,
      name: '醋溜丸子',
      price: 12.2,
      num: 39
    },
    {
      id: 3,
      name: '杂粮煎饼',
      price: 12.2,
      num: 12
    },
  ]

  build() {
    Row() {
      Column() {
        ForEach(this.foodList, (item: Food, index: number) => {
          Row() {
            Text(item.name).textStyle()
            Text(item.price.toString()).textStyle()
            Text(item.num.toString()).textStyle()
          }
          .width('100%')
          .padding({
            top: 10,
            bottom: 10
          })
        })
        ButtonBottom({myFoodList: $foodList})
      }
      .width('100%')
    }
    .height('100%')
  }
}

@Extend(Text)
function textStyle() {
  .layoutWeight(1).textAlign(TextAlign.Center).fontSize(20)
}

@Component
struct ButtonBottom {
  @Link
  myFoodList: Food[]
  build() {
    Button('更改数量')
      .onClick(() => {
        // this.myFoodList.forEach((item: Food) => {
        //   item.num++
        // })
        this.myFoodList = this.myFoodList.map((item: Food) => {
          item.num++
          return item
        })
      })
  }
}

class Food {
  id: number
  name: string
  price: number
  num: number
}
image.png
上一篇 下一篇

猜你喜欢

热点阅读