【HarmonyOS NEXT】textinput文本框如何实现分段展示手机号

【关键字】

textinput / 文本框 / 分段展示 / 手机号

【问题描述】

使用textinput文本框是否可以分段展示。有一个手机号输入框,希望可以分段展示手机号如下图所示。

cke_292.png

【解决方案】

可以考虑使用自定义键盘来支持,在自定义键盘中处理手机号码的格式。

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-basic-components-textinput-V5#%E7%A4%BA%E4%BE%8B6

示例代码:

@Entry
@Component
struct TextInputExample {
controller: TextInputController = new TextInputController()
@State inputValue: string = ""
// 自定义键盘组件
@Builder CustomKeyboardBuilder() {
Column() {
Button('确认').onClick(() => {
// 关闭自定义键盘
this.controller.stopEditing()
})
Grid() {
ForEach([1,2,3,4,5, 6, 7, 8, 9, '空格',0,"删除"], (item:number|string) => {
GridItem() {
Button(item + "")
.width(110).onClick(() => {
this.inputValue+=item;
//逻辑处理inputValue
})
}
})
}.maxCount(3).columnsGap(10).rowsGap(10).padding(5)
}.backgroundColor(Color.Gray)
}
build() {
Column() {
TextInput({ controller: this.controller, text: this.inputValue })
// 绑定自定义键盘
.customKeyboard(this.CustomKeyboardBuilder()).border({ width: 1 })
}
}
}

也可以在onChange事件中采用对数值格式进行处理(数据详细处理逻辑课根据业务需求完善),并通过text参数绑定变量做显示替换。

示例代码如下:

@Entry
@Component
struct TextInputExample {
controller: TextInputController = new TextInputController()
@State inputValue: string = ''
// 自定义键盘组件
build() {
Column() {
Text(this.inputValue)
TextInput({ controller: this.controller, text: $$this.inputValue})
.onChange(()=>{
this.inputValue=this.inputValue.toString().replace(/ /g, '');
if (this.inputValue.length>11) {
this.inputValue = this.inputValue.substring(0, 3) + ' ' + this.inputValue.substring(3, 7) + ' ' + this.inputValue.substring(7, 11);
}else if (this.inputValue.length>7) {
this.inputValue = this.inputValue.substring(0, 3) + ' ' + this.inputValue.substring(3, 7) + ' ' + this.inputValue.substring(7)
}else if (this.inputValue.length>3) {
this.inputValue = this.inputValue.substring(0, 3) + ' ' + this.inputValue.substring(3)
}
})
}
}
}

说明:文本框类型是number,此时支持纯数字。可以考虑使用Normal类型。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值