📌 场景介绍
步进器(Stepper)常用于数量调整、设置值选择等场景,特点是:
-
点击 + / - 调整值
-
支持最大值、最小值限制
-
支持禁用态
🧱 目录结构
/entry/src/main/ets
├── common/components/
│ └── Stepper.ets // 步进器组件
├── pages/
│ └── StepperDemo.ets // 示例页面
🧩 Stepper.ets 步进器组件
@Component
export struct Stepper {
@Prop min: number = 0
@Prop max: number = 10
@Prop step: number = 1
@Prop modelValue: number = 0
@Prop onChange: (val: number) => void = () => {}
build() {
Row() {
// 减
Button("-")
.enabled(this.modelValue > this.min)
.onClick(() => {
const val = Math.max(this.min, this.modelValue - this.step)
this.onChange(val)
})
Text(`${this.modelValue}`)
.width(50)
.textAlign(TextAlign.Center)
.fontSize(18)
.margin({ left: 10, right: 10 })
// 加
Button("+")
.enabled(this.modelValue < this.max)
.onClick(() => {
const val = Math.min(this.max, this.modelValue + this.step)
this.onChange(val)
})
}
.height(50)
.padding(5)
.backgroundColor('#f6f6f6')
.borderRadius(8)
.alignItems(VerticalAlign.Center)
}
}
🧩 StepperDemo.ets 示例页面
@Entry
@Component
struct StepperDemo {
@State value: number = 2
build() {
Column() {
Text(`当前值:${this.value}`).fontSize(20).margin({ bottom: 20 })
Stepper({
min: 1,
max: 5,
step: 1,
modelValue: this.value,
onChange: (val: number) => {
this.value = val
}
})
}
.padding(30)
.height('100%')
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
}
}
✅ 效果说明
-
当前值范围在 1 ~ 5 之间
-
点击
+
或-
进行增减 -
达到边界时按钮自动禁用
🔧 拓展建议
-
输入框支持手动输入数值
-
支持小数 step(如 0.5)
-
添加回调事件
onMaxReached
、onMinReached