1. 程式人生 > 其它 >5️⃣標準計算器學習元件完結篇

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版