5️⃣标准计算器学习组件完结篇

时间:2022-05-26
本文章向大家介绍5️⃣标准计算器学习组件完结篇,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

注:转自Tuer白晓明,原文地址:https://ost.51cto.com/posts/10751

本系列文章共有五篇,细致描述了如何学习ArkUI组件实现计算器的功能,以下为正文

3.11 @State注解

@State装饰的变量是组件内部的状态数据,当这些状态数据被修改时,将会调用所在组件的build方法进行UI刷新。
@State状态数据具有以下特征:

  • 支持多种类型:允许classnumberbooleanstring强类型的按值和按引用类型。允许这些强类型构成的数组,即Array<class>Array<string>Array<boolean>Array<number>。不允许objectany
  • 支持多实例:组件不同实例的内部状态数据独立。
  • 内部私有:标记为@State的属性时私有变量,只能在组件内访问。
  • 需要本地初始化:必须为所有@State变量分配初始值,将变量保持未初始化可能导致框架行为未定义。
  • 创建自定义组件时支持通过状态变量名设置初始值:在创建组件实例时,可以通过变量名显式指定@State状态属性的初始值。
// 实现点击按钮更改文本内容,显示点击次数
@Entry
@Component
struct StateExample {
  @State clickNum: number = 0;

  build() {
    Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
      Button(`这是第${this.clickNum}次点击按钮`)
        .fontSize(25)
        .fontWeight(FontWeight.Bold)
        .height(64)
        .onClick(() => {
          this.clickNum++;
        })
    }
    .width('100%')
    .height('100%')
  }
}
 

3.12 实现标准计算器的简单计算

首先定义两个变量:numeric用于显示运算表达式;total用于显示计算结果。
接着定义计算方法:calc(numeric: string){}
然后在数字按钮以及运算符号按钮添加点击事件:

// 如数字 7 
            Button('7', {type: ButtonType.Circle})
              .width(64).height(64)
              .fontSize(20).fontColor('#000').fontWeight(FontWeight.Bold)
              .backgroundColor('#FFFDFD')
              .borderRadius(32)
              .shadow({radius: 16, color: 0x7D7B7B, offsetX: 0, offsetY: 2})
              .onClick(() => {
                this.numeric += "7";
              })
// 如运算符号 +
            Button('+', {type: ButtonType.Circle})
              .width(64).height(64)
              .fontSize(32).fontColor('#1296DB').fontWeight(FontWeight.Bold)
              .backgroundColor('#FFFDFD')
              .borderRadius(32)
              .shadow({radius: 16, color: 0x7D7B7B, offsetX: 0, offsetY: 2})
              .onClick(() => {
                this.numeric += "+";
              })
 

最后在等号事件中调用运算方法:

              Button('=', {type: ButtonType.Capsule})
                .width(64).height(148)
                .fontSize(32).fontColor(0x1296DB).fontWeight(FontWeight.Bold)
                .backgroundColor('#FFFDFD')
                .borderRadius(32)
                .shadow({radius: 16, color: 0x7D7B7B, offsetX: 0, offsetY: 2})
                .onClick(() => {
                  if (this.numeric === '') {
                    return false;
                  }
                  this.numeric += "=";
                  this.total = this.calc(this.numeric).toString();
                })
 

小结

通过一个标准计算器的功能实现,从中学习了FlexColumnRow容器组件,以及TextButtonImage组件的属性和方法,并结合Demo进行说明。数据的状态管理,我们使用了@State装饰器,同时也对@Entry@Component装饰器做了说明。

对于计算器的其他能力,后续会继续完善,但不会再以文章的形式做说明,如果你感兴趣,可以到这儿下载:
OpenHarmony计算器-ETS版

原文地址:https://www.cnblogs.com/zhuwei0904/p/16315205.html