HarmonyOS 状态管理V2 @Event

@Event实现子传父

类似于vue的子传父,在鸿蒙中可以使用状态管理V2提供的@Event实现父子组件数据传递。
需要做以下事情:

  1. 父组件props传参的时候重写子组件的操作函数
  2. 子组件用@Event修饰该函数,表示需要传入更新数据源的回调函数
@Entry
@ComponentV2
struct Index {
  @Local title: string = "Titile One";
  @Local fontColor: Color = Color.Red;

  build() {
    Column() {
      Child({
        title: this.title,
        fontColor: this.fontColor,
        changeFactory: (type: number) => {
          if (type == 1) { // 操作对应数据
            this.title = "Title One";
            this.fontColor = Color.Red;
          } else if (type == 2) {
            this.title = "Title Two";
            this.fontColor = Color.Green;
          }
        }
      })
    }
  }
}

@ComponentV2
struct Child {
  @Param title: string = '';
  @Param fontColor: Color = Color.Black;
  @Event changeFactory: (x: number) => void = (x: number) => {
  }; // 回调函数的自定义实现(不写会自动生成一个默认函数)

  build() {
    Column() {
      Text(`${this.title}`)
        .fontColor(this.fontColor)
      Button("change to Title Two")
        .onClick(() => {
          this.changeFactory(2);
        })
      Button("change to Title One")
        .onClick(() => {
          this.changeFactory(1);
        })
    }
  }
}

这样子组件就可以调用父组件上重写的changeFactory函数去修改父组件的相应数据。

做出更改和传会子组件是异步的

调用回调函数后父组件的值会立刻更改,但是只有在父组件决定实际处理后才会在渲染前传回子组件。
官方文档的示例:

@ComponentV2
struct Child {
  @Param index: number = 0;
  @Event changeIndex: (val: number) => void;

  build() {
    Column() {
      Text(`Child index: ${this.index}`)
        .onClick(() => {
          this.changeIndex(20);
          console.log(`after changeIndex ${this.index}`); // 还是0
        })
    }
  }
}
@Entry
@ComponentV2
struct Index {
  @Local index: number = 0;

  build() {
      Column() {
        Child({
          index: this.index,
          changeIndex: (val: number) => {
            this.index = val;
          console.log(`in changeIndex ${this.index}`); // 20——父组件值立刻更改
          }
        })
      }
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yyt363045841

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值