1、 效果图
2、代码实现示例
import { hdHttp } from '../utils/Request'
import { router } from '@kit.ArkUI'
import { BasicConstant } from '../constants/BasicConstant '
import { prompt } from '../../pages/register/Register'
interface codeOne {
str: string ,
isBorder: boolean
}
export interface authEmailParam {
authCode: string
}
@Component
export struct TextInputCodeView {
// 验证码
@State code: string = ''
// 验证码位数
someArray: number[] = [1, 2, 3, 4]
@Prop email: string
// 校验验证码
async authCode(authCode: string) {
try {
let emailParam = await hdHttp.get<authEmailParam>('verifyEmail', { authCode: authCode } as authEmailParam)
return emailParam.success
} catch (e) {
return false
}
}
build() {
Stack() {
Row() {
ForEach(this.someArray, (item: number) => {
if (item != 1) Blank()
//填写验证码
if (this.code.length >= item) {
this.OneText({ str:this.code.substring(item - 1, item), isBorder: item === this.someArray.length})
} else {
//没有验证码
this.OneText({ str:'', isBorder: this.code.length + 1 === item })
}
})
}
.width('100%')
TextInput({ placeholder: "" })
.width('100%')
.height('100%')
.maxLength(this.someArray.length)
.caretColor(Color.Transparent)
.fontColor(Color.Transparent)
.borderColor(Color.Transparent)
.backgroundColor(Color.Transparent)
.onChange((value) => {
this.code = value
})
.onSubmit(async () => {
if (this.code.length === this.someArray.length) {
let res = await this.authCode(this.code)
if (res) {
prompt('验证码正确')
router.pushUrl({
url: BasicConstant.PAGE_SETAPASSWORD,
params: {
email: this.email
}
})
} else {
prompt('验证码错误')
}
}
})
}
.width('100%')
.height(60)
}
@Builder OneText(item:codeOne) {
//判断,是否选中当前的输入框,是否有内容。是当前选中的,没有内容,显示 |
Text(item.isBorder && !item.str ? '|' : item.str)
.width(50)
.height(70)
.textAlign(TextAlign.Center)
.fontSize(30)
.fontWeight(600)
.fontColor(item.isBorder && !item.str ?'#ffdd4f46' : Color.Black)
.backgroundColor('#f3f4f6')
.borderRadius(8)
}
}