1. 引言
在鸿蒙 ArkUI 开发中,TextInput
是一个常用的输入框组件,支持单行、多行输入、密码输入等多种类型,广泛用于登录、表单、搜索框等场景。本文将详细讲解 TextInput
的使用方法,并结合实际应用场景提供示例。
2. 基本使用
TextInput
组件用于接受用户输入文本,最简单的示例如下:
import { Component, State } from '@ohos.arkui';
@Component
struct BasicTextInput {
@State inputValue: string = '';
build() {
Column({ space: 10 }) {
Text('请输入内容:')
.fontSize(18)
.textColor('#333333');
TextInput({ placeholder: '请输入文本' })
.onInput(value => this.inputValue = value)
.borderRadius(5)
.backgroundColor('#F0F0F0')
.padding(10)
.width('90%');
Text(`你输入的是: ${this.inputValue}`)
.fontSize(16)
.textColor('#666666');
}
.padding(20)
.alignItems('center');
}
}
代码解析
placeholder
: 设置输入框的占位文本。onInput
: 监听输入变化,并更新@State
变量。borderRadius
、backgroundColor
、padding
: 用于美化输入框。width('90%')
: 使输入框宽度适配。
3. 进阶功能
3.1 密码输入框
如果需要输入密码,可以设置 type: 'password'
,以隐藏输入内容:
TextInput({ placeholder: '请输入密码', type: 'password' })
.onInput(value => this.inputValue = value)
.borderRadius(5)
.backgroundColor('#F0F0F0')
.padding(10)
.width('90%');
3.2 多行文本输入
如果需要支持多行输入(如备注、留言),可以使用 multiline: true
:
TextInput({ placeholder: '请输入留言', multiline: true })
.onInput(value => this.inputValue = value)
.borderRadius(5)
.backgroundColor('#F0F0F0')
.padding(10)
.width('90%')
.height(100);
3.3 限制输入长度
可以通过 maxLength
限制输入的最大字符数,例如限制 20 个字符:
TextInput({ placeholder: '最多输入 20 个字符', maxLength: 20 })
.onInput(value => this.inputValue = value)
.width('90%');
3.4 监听焦点事件
可以使用 onFocus
和 onBlur
监听输入框的焦点状态,例如在获取焦点时更改背景色:
TextInput({ placeholder: '点击输入' })
.onFocus(() => console.log('输入框获得焦点'))
.onBlur(() => console.log('输入框失去焦点'))
.borderRadius(5)
.backgroundColor('#F0F0F0')
.padding(10)
.width('90%');
3.5 输入验证
可以在 onInput
事件中添加输入验证,例如限制只能输入数字:
TextInput({ placeholder: '请输入数字' })
.onInput(value => {
if (/^[0-9]*$/.test(value)) {
this.inputValue = value;
}
})
.width('90%');
4. 结合 Button 实现搜索框
在实际应用中,TextInput
也可以与 Button
结合,构建一个简单的搜索框:
@Component
struct SearchBar {
@State searchText: string = '';
build() {
Row({ space: 10 }) {
TextInput({ placeholder: '请输入搜索内容' })
.onInput(value => this.searchText = value)
.borderRadius(5)
.backgroundColor('#F0F0F0')
.padding(10)
.width('70%');
Button('搜索')
.onClick(() => console.log(`搜索内容: ${this.searchText}`))
.backgroundColor('#007BFF')
.textColor('#FFFFFF')
.borderRadius(5)
.padding(10);
}
.padding(20)
.alignItems('center');
}
}
5. 总结
本文详细介绍了 ArkUI TextInput
组件的各种应用场景,包括基本用法、密码输入、多行文本输入、字符限制、焦点监听、输入验证等。同时,我们还结合 Button
组件,实现了一个简单的搜索框。合理使用 TextInput
组件可以提高用户体验,使输入交互更加友好。
在实际开发中,可以结合 TextInput
的 onInput
事件进行更复杂的输入处理,例如与 API 交互、输入自动补全等,灵活应用 TextInput
组件能够极大提升鸿蒙应用的用户体验。