目录

TextInput组件如何使用showError展示错误文本

问题现象

如何实现TextInput在用户输入错误时自动显示错误信息和调整UI布局?

问题截图如下:

背景知识

解决方案

1.使用状态变量修饰error,在onChange()回调里将需提示的错误文本赋值error,即可实现自动显示错误信息。

2.文本组件设置alignSelf(ItemAlign.Start),实现提示错误文本时,UI跟随调整。

@Entry
@Component
struct ShowError {
  @State password: string = '';
  @State error: string = '';
  controller: TextInputController = new TextInputController();

  build() {
    Column() {
      Row() {
        Text('密码:')
          .fontSize(18)
          .textAlign(TextAlign.Center)
          .alignSelf(ItemAlign.Start)
          .height(50);

        TextInput({ placeholder: '请输入密码', text: $$this.password, controller: this.controller })
          .height(50)
          .showError(this.error)
          .newExtend()
          .borderRadius(20)
          .onChange((value: string) => {
            this.error = value;
            this.password = value;
          });
      }
      .margin(10);
    }
    .justifyContent(FlexAlign.Center)
    .height('100%')
    .width('100%')
    .expandSafeArea([SafeAreaType.SYSTEM], [SafeAreaEdge.TOP, SafeAreaEdge.BOTTOM])
    .backgroundColor('#F1F3F5');
  }
}


// 自定义属性
@Extend(TextInput)
function newExtend() {
  .layoutWeight(1)
  .placeholderColor('#99182431')
  .backgroundColor('#F1F3F5')
  .width('100%')
  .fontSize(14)
  .copyOption(CopyOptions.InApp)
  .borderWidth(1);
}