文本输入(TextInput/TextArea)

2024-01-25 13:16 更新

TextInput、TextArea是输入框组件,通常用于响应用户的输入操作,比如评论区的输入、聊天框的输入、表格的输入等,也可以结合其它组件构建功能页面,例如登录注册页面。具体用法参考TextInputTextArea

创建输入框

TextInput为单行输入框、TextArea为多行输入框。通过以下接口来创建。

  1. TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: TextAreaController})
  1. TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: TextInputController})
  • 单行输入框
    1. TextInput()

  • 多行输入框
    1. TextArea()

    多行输入框文字超出一行时会自动折行。

    1. TextArea({text:"我是TextArea我是TextArea我是TextArea我是TextArea"}).width(300)

设置输入框类型

TextInput有5种可选类型,分别为Normal基本输入模式、Password密码输入模式、Email邮箱地址输入模式、Number纯数字输入模式、PhoneNumber电话号码输入模式。通过type属性进行设置:

  • 基本输入模式(默认类型)
    1. TextInput()
    2. .type(InputType.Normal)

  • 密码输入模式
    1. TextInput()
    2. .type(InputType.Password)

自定义样式

  • 设置无输入时的提示文本。

    TextInput({placeholder:'我是提示文本'})

    1. TextInput({placeholder:'我是提示文本'})

  • 设置输入框当前的文本内容。
    1. TextInput({placeholder:'我是提示文本',text:'我是当前文本内容'})

  • 添加backgroundColor改变输入框的背景颜色。
    1. TextInput({placeholder:'我是提示文本',text:'我是当前文本内容'})
    2. .backgroundColor(Color.Pink)

    更丰富的样式可以结合通用属性实现。

添加事件

文本框主要用于获取用户输入的信息,把信息处理成数据进行上传,绑定onChange事件可以获取输入框内改变的内容。用户也可以使用通用事件来进行相应的交互操作。

  1. TextInput()
  2. .onChange((value: string) => {
  3. console.info(value);
  4. })
  5. .onFocus(() => {
  6. console.info('获取焦点');
  7. })

场景示例

用于表单的提交,在用户登录/注册页面,用户的登录或注册的输入操作。

  1. @Entry
  2. @Component
  3. struct TextInputSample {
  4. build() {
  5. Column() {
  6. TextInput({ placeholder: 'input your username' }).margin({ top: 20 })
  7. .onSubmit((EnterKeyType)=>{
  8. console.info(EnterKeyType+'输入法回车键的类型值')
  9. })
  10. TextInput({ placeholder: 'input your password' }).type(InputType.Password).margin({ top: 20 })
  11. .onSubmit((EnterKeyType)=>{
  12. console.info(EnterKeyType+'输入法回车键的类型值')
  13. })
  14. Button('Sign in').width(150).margin({ top: 20 })
  15. }.padding(20)
  16. }
  17. }

以上内容是否对您有帮助:
在线笔记
App下载
App下载

扫描二维码

下载编程狮App

公众号
微信公众号

编程狮公众号