使用TextInput和bindPopup如何实现带动态提示的输入框。需要实现以下效果:
实现气泡占用全屏时TextInput可以输入文本的效果,参考以下步骤:
@State message: string = '';
@State customPopup: boolean = false;
@Builder popupBuilder() { Row({ space: 2 }) { Text(this.tips).fontSize(15); } .alignItems(VerticalAlign.Center) .justifyContent(FlexAlign.Center) .width('100%') .height('100%') // popup显示时占用整个窗口 .padding(5); }
build() { Column() { TextInput({ text: this.message, placeholder: '请输入姓名' }) .margin({ top: 50, left: 15, right: 15 }) .enableAutoFill(false) .bindPopup(this.customPopup, { builder: this.popupBuilder, placement: Placement.Bottom, mask: { color: '#33000000' }, backgroundBlurStyle: BlurStyle.NONE, // 去除模糊背景填充效果 enableArrow: false, // 隐藏箭头 autoCancel: true, showInSubWindow: false, onStateChange: (e) => { if (!e.isVisible) { this.customPopup = false; // 点击了弹出框外部的区域,及时地将@State变量同步更新为false } } }) .onChange((value: string) => { this.message = value; if (value.length == 0) { this.tips = ''; return; } if (!isChineseCharByRegex(value)) { this.tips = '您的输入有误,姓名只能为汉字'; } else { this.tips = ''; } }) .onEditChange((isEditing: boolean) => { // isEditing为true表示输入框获得了焦点 if (isEditing) { // 只有获得焦点才显示 this.customPopup = true; } else { this.customPopup = false; // 输入框失去焦点时隐藏 } }); } .width('100%') .height('100%'); }
完整示例参考如下:
@Entry @Component struct BindPopUpDemo { @State message: string = ''; @State customPopup: boolean = false; @State tips: string = ''; @Builder popupBuilder() { Row({ space: 2 }) { Text(this.tips).fontSize(15); } .alignItems(VerticalAlign.Center) .justifyContent(FlexAlign.Center) .width('100%') .height('100%') // popup显示时占用整个窗口 .padding(5); } build() { Column() { TextInput({ text: this.message, placeholder: '请输入姓名' }) .margin({ top: 50, left: 15, right: 15 }) .enableAutoFill(false) .bindPopup(this.customPopup, { builder: this.popupBuilder, placement: Placement.Bottom, mask: { color: '#33000000' }, backgroundBlurStyle: BlurStyle.NONE, // 去除模糊背景填充效果 enableArrow: false, // 隐藏箭头 autoCancel: true, showInSubWindow: false, onStateChange: (e) => { if (!e.isVisible) { this.customPopup = false; // 点击了弹出框外部的区域,及时地将@State变量同步更新为false } } }) .onChange((value: string) => { this.message = value; if (value.length == 0) { this.tips = ''; return; } if (!isChineseCharByRegex(value)) { this.tips = '您的输入有误,姓名只能为汉字'; } else { this.tips = ''; } }) .onEditChange((isEditing: boolean) => { // isEditing为true表示输入框获得了焦点 if (isEditing) { // 只有获得焦点才显示 this.customPopup = true; } else { this.customPopup = false; // 输入框失去焦点时隐藏 } }); } .width('100%') .height('100%'); } } function isChineseCharByRegex(char: string): boolean { return /^[\u4e00-\u9fa5\u3400-\u4dbf\ud840-\ud87f\udc00-\udfff\uF900-\uFAFF]+$/.test(char); }