TextInput组件如何收键盘的同时光标也消失(HarmonyOS 鸿蒙Next)

TextInput组件如何收键盘的同时光标也消失(HarmonyOS 鸿蒙Next) TextInput组件如何收键盘的同时光标也消失

2 回复

你可以将焦点转移到其他组件上,参考以下示例

import promptAction from '@ohos.promptAction'
@Entry
@Component
struct TextInputExample {
  @State text: string = ''
  controller: TextInputController = new TextInputController()
  build() {
    Column() {
      TextInput({ text: this.text, placeholder: '请输入用户名', controller: this.controller })
        .height(40)
        .margin(20)
        .fontSize(14)
        .width('90%')
      Button('弹出toast')
        .onClick(() => {
          // 焦点转移到button上
          focusControl.requestFocus('button')
          promptAction.showToast({
            message: '我是toast',
            duration: 2000
          })
        }).width('30%').key('button')
    }
    .width('100%')
    .height('100%')
  }
}

更多关于TextInput组件如何收键盘的同时光标也消失(HarmonyOS 鸿蒙Next)的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,要使TextInput组件在收起键盘的同时光标也消失,可以通过调用TextInput组件的onBlur事件来实现。onBlur事件在输入框失去焦点时触发,可以在该事件中设置TextInputfocus属性为false,从而使光标消失。

具体代码如下:

import { TextInput } from '@ohos/text';

export default {
  data: {
    inputText: ''
  },
  onBlur() {
    this.$refs.textInput.focus = false;
  }
};

在布局文件中,将TextInput组件的onBlur事件绑定到onBlur方法:

<TextInput
  ref="textInput"
  value="{{inputText}}"
  onBlur="onBlur"
/>

当用户收起键盘时,onBlur事件会被触发,TextInput组件的focus属性被设置为false,光标随之消失。

回到顶部