【关键字】
textinput / 文本框 / 分段展示 / 手机号
【问题描述】
使用textinput文本框是否可以分段展示。有一个手机号输入框,希望可以分段展示手机号如下图所示。
【解决方案】
可以考虑使用自定义键盘来支持,在自定义键盘中处理手机号码的格式。
示例代码:
@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类型。