鸿蒙-自定义验证码组件实现方案
1.创建验证码组件VerificationCodeInput.ets。
·
效果图展示

1.创建验证码组件 VerificationCodeInput.ets
@Component
struct VerificationCodeInput {
onFinishInput?: (value: string) => void
@State inputValue: string[] = ["", "", "", ""]
@State inputEnable: boolean[] = [true, false, false, false]
inputIndex: number[] = [0, 1, 2, 3]
build() {
Row() {
ForEach(this.inputIndex, (index: number) => {
TextInput({ text: this.inputValue[index] })
.textInputStyle(this.inputEnable[index])
.id(index.toString())
.onDidDelete((_) => {
if (this.inputValue[index].length == 0) {
//不是第一个输入框 且 输入框内没有文字,则删除上一个输入框内容,并且使上一个输入框获取焦点
if (index != 0) {
this.inputValue[index-1] = ""
this.inputEnable[index] = false
this.inputEnable[index-1] = true
this.getUIContext().getFocusController().requestFocus((index - 1).toString())
} else {
//如果输入框内有文字,则只删除当前输入框内容
this.inputValue[index] = ""
}
}
})
.onChange((value: string) => {
this.inputValue[index] = value
if (value.length == 1) {
if (index != 3) {
this.inputEnable[index+1] = true
this.getUIContext().getFocusController().requestFocus((index + 1).toString())
} else {
if (this.onFinishInput) {
let result = ""
for (let i = 0; i < this.inputValue.length; i++) {
result += this.inputValue[i]
}
this.onFinishInput(result)
}
}
}
})
})
}.onAppear(() => {
this.getUIContext().getFocusController().requestFocus("0")
})
.width('100%')
.justifyContent(FlexAlign.SpaceBetween)
}
}
@Extend(TextInput)
function textInputStyle(enable: boolean) {
.border({
width: 1,
color: enable ? "#F28E1B" : "#999999",
radius: 5,
style: BorderStyle.Solid,
})
.textAlign(TextAlign.Center)
.maxLength(1)
.maxLines(1)
.type(InputType.Number)
.width(60)
.height(60)
.fontSize(28)
.fontWeight(FontWeight.Bold)
.backgroundColor('#FFFFFF')
.caretColor('#999999') // 关键属性:设置光标颜色为红色
}
export { VerificationCodeInput }
2.组件使用
import { VerificationCodeInput } from '../../components/VerificationCodeInput'
@Entry
@Component
struct LoginCode {
code: string = ''
build() {
Column() {
Row() {
VerificationCodeInput({
onFinishInput: (val) => {
this.code = val
}
})
}
.width('85%')
}
.height('100%')
.width('100%')
}
}
更多推荐


所有评论(0)