在 OpenHarmony(ArkTS / eTS) 中,“验证码”本身并不是系统提供的固定组件,通常是通过 自定义组件 + 逻辑控制 来实现的。下面从常见验证码类型和自定义方式给你一个完整说明。
短信 / 邮箱验证码
图形验证码(自定义绘制)
滑块验证码
输入型验证码(6 位框)
@Component
struct CodeInput {
@State code: string = ''
length: number = 6
onComplete?: (code: string) => void
build() {
Row({ space: 10 }) {
ForEach(Array(this.length), (_, index) => {
Text(this.code[index] ?? '')
.width(40)
.height(48)
.fontSize(20)
.textAlign(TextAlign.Center)
.border({ width: 1, color: '#999' })
})
}
.justifyContent(FlexAlign.Center)
.onClick(() => {
// 可调用输入法
})
}
}
⚠️ 实际项目中通常结合 TextInput(隐藏样式)来获取输入。
TextInput()
.type(InputType.Number)
.maxLength(6)
.opacity(0)
.onChange((value) => {
this.code = value
if (value.length === 6) {
this.onComplete?.(value)
}
})
Canvas(this.context)
.width(120)
.height(40)
.onReady(() => {
const ctx = this.context
ctx.clearRect(0, 0, 120, 40)
ctx.font = '24px sans-serif'
ctx.fillText(this.randomCode(), 10, 30)
// 画干扰线
})
生成随机码:
randomCode(): string {
return Math.random().toString(36).slice(2, 6)
}
@State count: number = 60
Button(this.count > 0 ? `${this.count}s` : '获取验证码')
.enabled(this.count === 0)
.onClick(() => {
this.count = 60
const timer = setInterval(() => {
this.count--
if (this.count === 0) clearInterval(timer)
}, 1000)
})
✅ 验证码 不是系统组件
✅ 核心逻辑:
@State)如果你有具体需求,比如:
可以告诉我,我可以直接给你 完整可运行示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。