鸿蒙Harmony OS Next原生开发通过案例了解什么叫声明式变量

鸿蒙初开,开天辟地

第一个应用接触鸿蒙

@Component
export default struct My {
  @State isOn:boolean = false;
  build() {
    Column(){
      if(this.isOn){
        Image("https://i-blog.csdnimg.cn/direct/9ed16dcd083d4e70a240adba82a6e8d4.png").height(500);
      }
      else{
        Image("https://i-blog.csdnimg.cn/direct/68863ed506f6426b942d45b082c9ff64.png").height(500);
      }
      Row(){
        Button("开灯").onClick(()=>{
          this.isOn = true;
        });
        Button('关灯').onClick(()=>{
          this.isOn = false;
        });
      }
    }
    .height('100%')
    .width('100%')
  }
}

@Component
export default struct My {
  @State isOn:boolean = false;
  build() {
    Column(){
      if(this.isOn){
        Image("https://i-blog.csdnimg.cn/direct/9ed16dcd083d4e70a240adba82a6e8d4.png").height(500);
      }
      else{
        Image("https://i-blog.csdnimg.cn/direct/68863ed506f6426b942d45b082c9ff64.png").height(500);
      }
      Row(){
        Button("开灯").onClick(()=>{
          this.isOn = true;
        });
        Button('关灯').onClick(()=>{
          this.isOn = false;
        });
      }
    }
    .height('100%')
    .width('100%')
  }
}

         ​​​​​​​        ​​​​​​​        ​​​​​​​        ​​​​​​​        ​​​​​​​        ​​​​​​​        

此处为默认的isOn为false状态,即我们在@State isOn:boolean = false;声明的false值

当我们通过两个按钮组件绑定的onclick触发修改声明变量的值后,相对应的,我们的页面布局效果也产生了变化

        Button("开灯").onClick(()=>{
          this.isOn = true;
        });
        Button('关灯').onClick(()=>{
          this.isOn = false;
        });

此时,因为@State isOn:boolean的值已经变为了True

所以显示的图片就一并更改为true所对应的图片了

        if(this.isOn){
        Image("https://i-blog.csdnimg.cn/direct/9ed16dcd083d4e70a240adba82a6e8d4.png").height(500);
      }
      else{
        Image("https://i-blog.csdnimg.cn/direct/68863ed506f6426b942d45b082c9ff64.png").height(500);
      }

在这里的小应用中,我们通过控制isOn变量的值为True或False就实现了图片的切换效果,和JS不同,ArkTs触发方法,最终是通过修改声明变量的方式实现了具体的效果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值