HarmonyOS NEXT - ArkUI: TextInput组件

TextInput组件用于输入单行文本,使用非常广泛,例如应用登录账号密码、发送消息等。

TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: TextInputController})
  • placeholder:设置提示
  • text:设置文本
  • controller:设置TextInput控制器

设置输入类型

.type(value: InputType)

InputType枚举类型:

  • InputType.Normal:基本输入模式。支持输入数字、字母、下划线、空格、特殊字符。
  • InputType.Password:密码输入模式。
  • InputType.Email:e-mail地址输入模式。
  • InputType.Number:纯数字输入模式。

获取输入文本 设置onChange事件,输入文本发生变化时触发onChange事件执行回调函数。

.onChange(callback: EditableTextOnChangeCallback)

代码实例:TextInputPage

@Entry
@Component
struct TextInputPage {
  @State message: string = '第2节 TextInput组件';
  @State phone:string='';

  build() {
    Column({space:6}) {
      Text(this.message)
        .fontSize(30)
        .fontWeight(FontWeight.Bold)

      TextInput({placeholder:'请输入账号'})
      TextInput({text:'设置初始值'})
      TextInput({placeholder:'请输入密码'})
        .type(InputType.Password)
      TextInput({placeholder:'请输入手机号'})
        .type(InputType.Number)
        .onChange((value:string)=>{
          this.phone=value
        })
      Text('手机号码是:'+this.phone)
    }
    .height('100%')
    .width('100%')
  }
}

设置当通过InputCounterOptions输入的字符数超过阈值时显示计数器。

showCounter(value: boolean, options?: InputCounterOptions)
  • 参数value为true时,才能设置options,文本框开启计数下标功能,需要配合maxLength(设置最大字符限制)一起使用。字符计数器显示的效果是当前输入字符数/最大可输入字符数。
  • 当输入字符数大于最大字符数乘百分比值时,显示字符计数器。如果用户设置计数器时不设置InputCounterOptions,那么当前输入字符数超过最大字符数时,边框和计数器下标将变为红色。用户同时设置参数value为true和InputCounterOptions,当thresholdPercentage数值在有效区间内,且输入字符数超过最大字符数时,边框和计数器下标将变为红色,框体抖动。highlightBorder设置为false,则不显示红色边框,计数器默认显示红色,框体抖动。
  • 内联模式和密码模式下字符计数器不显示。

代码实例:通过maxLength、showCounter、showUnderline属性实现了计数器的功能。

@Entry
@Component
struct TextInputPage2 {
  @State text: string = '';
  controller: TextInputController = new TextInputController();

  build() {
    Column() {
      TextInput({ text: this.text, controller: this.controller })
        .placeholderFont({ size: 16, weight: 400 })
        .width(336)
        .height(56)
        .maxLength(6)
        .showUnderline(true)
        .showCounter(true,
          { thresholdPercentage: 50, highlightBorder: true })//计数器显示效果为用户当前输入字符数/最大字符限制数。最大字符限制数通过maxLength()接口设置。
          //如果用户当前输入字符数达到最大字符限制乘50%(thresholdPercentage)。字符计数器显示。
          //用户设置highlightBorder为false时,配置取消红色边框。不设置此参数时,默认为true。
        .onChange((value: string) => {
          this.text = value;
        })
    }.width('100%').height('100%').backgroundColor('#F1F3F5')
  }
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
03-30 21:42
京东 1 n*19 本科其他
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务