美文网首页
鸿蒙开发-Link使用

鸿蒙开发-Link使用

作者: 激扬飞雪 | 来源:发表于2024-05-20 21:24 被阅读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

    相关文章

      网友评论

          本文标题:鸿蒙开发-Link使用

          本文链接:https://www.haomeiwen.com/subject/trmnfjtx.html