目录

TextInput组件如何实现文本默认选中效果

问题现象

页面初次构建完成时,如何使TextInput组件获取焦点并且默认文本全部选中?

效果预览

背景知识

解决方案

  1. 使用defaultFocus属性可使TextInput组件在页面初次构建完成时自动获取焦点。
  2. 配合setTextSelection方法设置文本选择区域并高亮显示实现文本默认选中效果。

示例参考如下:

@Entry
@Component
struct SelectedIndex {
  text: string = 'Hello World';
  controller: TextInputController = new TextInputController();

  build() {
    Row() {
      TextInput({
        text: '选中默认文本内容',
        placeholder: 'input your word...',
        controller: this.controller
      })
        .width('100%')
        .defaultFocus(true) // 默认获取焦点
        .onFocus(() => {
          this.controller.setTextSelection(0, this.text.length); // 选择文本区域
        });
    }
    .padding({ left: 16, right: 16 })
    .width('100%')
    .height('100%');
  }
}

总结

setTextSelection要在TextInput组件获焦时执行才能生效。