HarmonyOS鸿蒙Next中TextInput的基本使用

HarmonyOS鸿蒙Next中TextInput的基本使用

@Entry
@Component
struct Page01_TextInput {
  @State username:string =''
  @State password:string =''
  build() {
    Column(){
      TextInput({placeholder:'输入用户名',text:this.username})
        .type(InputType.Normal)
        .backgroundColor(Color.Transparent)
        .borderRadius(0)
        .height(60)
        .border({
          width:{bottom:1}
        ,color:'#ccc'
        })
      
      TextInput({placeholder:'请输入密码',text:this.password})
        .type(InputType.Password)
        .height(60)
        .backgroundColor(Color.Transparent)
        .borderRadius(0)
        .border({
          width:{bottom:1}
        ,color:'#ccc'
        })
        .passwordIcon({
          onIconSrc:$r('app.media.ic_eyes_open'),
          offIconSrc:$r('app.media.ic_eyes_close')
        })

      Row({space:20}){
        Button('清空输入内容')
          .onClick(()=>{
            this.username=''
            this.password=''
          })

        Button('获取输入内容')
          .onClick(()=>{
            AlertDialog.show({
              message:`用户名:${this.username},密码:${this.password}`
            })
          })
      }
      .margin({top:10})
    }
    .padding(20)
  }
}

更多关于HarmonyOS鸿蒙Next中TextInput的基本使用的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

在HarmonyOS鸿蒙Next中,TextInput组件用于接收用户输入的文本。它支持多种属性来控制文本输入的行为和样式。以下是一些常用属性和方法:

  1. placeholder:设置输入框的占位符文本,用于提示用户输入内容。
  2. text:获取或设置输入框中的文本内容。
  3. maxLength:限制输入框的最大字符数。
  4. type:设置输入框的类型,如文本、密码、数字等。
  5. onChange:监听输入框内容变化的事件,当用户输入或删除文本时触发。
  6. onSubmit:监听用户按下回车键的事件。
  7. style:设置输入框的样式,包括宽度、高度、边框、颜色等。

示例代码如下:

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

@Entry
@Component
struct TextInputExample {
  @State text: string = '';

  build() {
    Column() {
      TextInput({ placeholder: '请输入内容', text: this.text })
        .maxLength(20)
        .type(InputType.Text)
        .onChange((value: string) => {
          this.text = value;
        })
        .onSubmit(() => {
          console.log('用户按下回车键');
        })
        .style({ width: '100%', height: 50, borderColor: '#000000', borderWidth: 1 });
    }
  }
}

上述代码创建了一个TextInput组件,设置了占位符文本、最大字符数、输入类型,并监听内容变化和回车键事件。通过style属性设置了输入框的样式。

更多关于HarmonyOS鸿蒙Next中TextInput的基本使用的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,TextInput组件用于接收用户输入的文本。基本使用步骤如下:

  1. 引入组件:在布局文件中引入TextInput组件。
  2. 设置属性:可以设置TextInput的属性,如hint(提示文本)、text(默认文本)、maxLength(最大长度)等。
  3. 事件监听:通过onChange事件监听用户输入的变化,获取输入内容。
  4. 样式定制:可以通过style属性自定义TextInput的外观样式。

示例代码:

<TextInput
    hint="请输入内容"
    text="默认文本"
    maxLength="100"
    onChange="onTextChange"
/>

在JS中处理onChange事件:

function onTextChange(event) {
    console.log("输入内容: " + event.value);
}

通过以上步骤,您可以在HarmonyOS中实现基本的文本输入功能。

回到顶部