# 5.8:计数器组件(Counter)

ArkUI 开发框架提供了 Counter 组件实现计数器功能,计数器的使用场景很常见,比如购物类 APP 在添加或者减少商品的时候会使用到计数器,它可以包含一个子组件,本节笔者简单介绍一下 Counter 的使用。

# 5.8.1:Counter 定义介绍

interface CounterInterface {
  (): CounterAttribute;
}
1
2
3

由源码可知,Counter 使用时暂不需要配置额外参数。

简单样例如下所示:

@Entry @Component struct ComponentTest {
  build() {
    Column() {
      Row() {
        Counter()         // 默认效果

        Counter() {       // 包含一个子组件
          Text('1')       // Text 默认值为 1
            .fontSize(18) // Text 字体大小
        }
      }
      .justifyContent(FlexAlign.SpaceAround)
      .width("100%")
    }
    .width("100%")
    .height("100%")
    .padding(10)
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

样例运行结果如下图所示:

5_8_1_1

# 5.8.2:Counter 事件介绍

declare class CounterAttribute extends CommonMethod<CounterAttribute> {
  onInc(event: () => void): CounterAttribute;
  onDec(event: () => void): CounterAttribute;
}
1
2
3
4

Counter 没有提供额外的属性方法,只提供了 onInc()onDec() 两个事件回调方法,各方法说明如下所示:

  • onInc:数字增加的事件回调。
  • onDec:数字减少的事件回调。

# 5.8.3:Counter 完整样例

@Entry @Component struct ComponentTest {

  @State value: number = 0

  build() {
    Column() {
      Counter() {
        Text(this.value.toString())
          .fontSize(18)
      }
      .onInc(() => {  // 自增操作
        this.value++;
      })
      .onDec(() => {  // 自减操作
        this.value--;
      })
    }
    .width("100%")
    .height("100%")
    .padding(20)
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

样例运行结果如下图所示:

5_8_2_1

📢:Counter 不支持通用事件和手势, 仅支持 onInc()onDec() 事件。

(adsbygoogle = window.adsbygoogle || []).push({});
请作者喝杯咖啡

津公网安备 12011402001367号

津ICP备2020008934号-2

中央网信办互联网违法和不良信息举报中心

天津市互联网违法和不良信息举报中心