HarmonyOS 页面有个input,不点击input,如何用代码触发焦点,使其打开键盘?

如题:HarmonyOS 页面有个input,不点击input,如何用代码触发焦点,使其打开键盘?

阅读 603
1 个回答

让某个输入框获取焦点可以使用sendEventByKey方法像该组件发送一个点击事件,以下是简单示例,点击获取验证码按钮,呼出键盘:

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

  build() {
    Column() {
      Row() {
        TextInput({
          text: this.text,
          placeholder: '请输入用户名',
          controller: this.controller
        })
          .height(40)
          .margin(20)
          .fontSize(14)
          .width('90%')
          .id('t1')
      }

      Row() {
        TextInput({ placeholder: '请输入密码' })
          .height(40)
          .margin(20)
          .type(InputType.Number)
          .maxLength(9)
          .width('60%')
          .id('t2')
        Button('获取验证码')
          .onClick(() => {
            /**
             *  id:要触发事件的组件的id
             * params: 事件参数,无参数传空字符串
             */
            sendEventByKey('t2', 10, '');
          })
          .width('30%')
      }
      .justifyContent(FlexAlign.SpaceBetween)
      .width('100%')
    }
  }
}

参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/ts-universal-attributes-component-id-V5

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进