如何设置 `Stepper` 的最小值、最大值和步长?

我想限制 Stepper 的可选值范围,比如商品数量最少是 1,最多是 10,并且每次只能加减 1。这怎么实现?

阅读 741
1 个回答

分享你个示例吧,你参考下:

限制范围 1-10,步长 1。

@Component
struct RangedStepper {
  @State count: number = 1; // 初始值
  readonly minValue: number = 1;
  readonly maxValue: number = 10;
  readonly stepValue: number = 1;

  build() {
    Column({ space: 10 }) {
      Text(`Count: ${this.count}`)
      Stepper({ index: this.count })
        .onNext(() => {
          // 检查是否超上限
          if (this.count + this.stepValue <= this.maxValue) {
            this.count += this.stepValue;
          }
        })
        .onPrevious(() => {
          // 检查是否低于下限
          if (this.count - this.stepValue >= this.minValue) {
            this.count -= this.stepValue;
          }
        })
        // 可能需要手动禁用按钮 (如果 Stepper 支持或自定义)
        // .previousButtonEnabled(this.count > this.minValue)
        // .nextButtonEnabled(this.count < this.maxValue)
    }
  }
}

边界检查和步长逻辑需要在事件回调中自行处理。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题