TextInput组件用于输入单行文本,响应输入事件。TextInput的使用也非常广泛,例如应用登录账号密码、发送消息等。和Text组件一样,TextInput组件也支持文本样式设置,下面的示例代码实现了一个简单的输入框:
@Entry
@Component
struct Index {
@State info: string = '一杯敬自由,一杯敬死亡。'
build() {
Row() {
Column() {
TextInput()
.fontColor(Color.Blue)
.fontSize(20)
.fontStyle(FontStyle.Italic)
.fontWeight(FontWeight.Bold)
.fontFamily('华文行楷')
}.width('100%')
.borderStyle(BorderStyle.Solid)
.borderWidth(2)
.borderColor('#C75450')
}
.width('100%')
.height('100%')
}
}
当我们平时使用输入框的时候,往往会有一些提示文字。例如登录账号的时候会有“请输入账号”这样的文本提示,当用户输入内容之后,提示文本就会消失,这种提示功能使用placeholder属性就可以轻松的实现。您还可以使用placeholderColor和placeholderFont分别设置提示文本的颜色和样式,示例代码如下:
@Entry
@Component
struct Index {
@State info: string = '一杯敬自由,一杯敬死亡。'
build() {
Row() {
Column() {
TextInput({ placeholder: '请输入信息' })
.fontColor(Color.Blue)
.fontSize(20)
.fontStyle(FontStyle.Italic)
.fontWeight(FontWeight.Bold)
.fontFamily('华文行楷')
}.width('100%')
.borderStyle(BorderStyle.Solid)
.borderWidth(2)
.borderColor('#C75450')
}
.width('100%')
.height('100%')
}
}
设置提示文字样式
TextInput({ placeholder: '请输入信息' }) .fontColor(Color.Blue) .fontSize(20) .fontStyle(FontStyle.Italic) .fontWeight(FontWeight.Bold) .fontFamily('华文行楷') .placeholderColor(0x999999) .placeholderFont({ size: 20, weight: FontWeight.Medium, family: '华文行楷', style: FontStyle.Italic })
可以使用type属性来设置输入框类型。例如密码输入框,一般输入密码的时候,为了用户密码安全,内容会显示为“......”,针对这种场景,将type属性设置为InputType.Password就可以实现。示例代码如下:
TextInput({ placeholder: '请输入密码' }) .type(InputType.Password)
效果图如下:
Normal:基本输入模式。支持输入数字、字母、下划线、空格、特殊字符。 Password:密码输入模式。 Email:e-mail地址输入模式。 Number:纯数字输入模式。
可以使用TextInputController动态设置光位置,下面的示例代码使用TextInputController的caretPosition方法,将光标移动到了第二个字符后。
@Entry
@Component
struct Index {
@State info: string = '一杯敬自由,一杯敬死亡。'
controller: TextInputController = new TextInputController()
build() {
Row() {
Column() {
TextInput({ controller: this.controller })
Button('设置光标位置')
.onClick(() => {
this.controller.caretPosition(2)
})
}.width('100%')
.borderStyle(BorderStyle.Solid)
.borderWidth(2)
.borderColor('#C75450')
}
.width('100%')
.height('100%')
}
}
我们可以给TextInput设置onChange事件,输入文本发生变化时触发回调,下面示例代码中的value为实时获取用户输入的文本信息。
@Entry @Component struct Index { @State info: string = '一杯敬自由,一杯敬死亡。' controller: TextInputController = new TextInputController() build() { Row() { Column() { TextInput({ placeholder: '请输入账号' }) .caretColor(Color.Blue) .onChange((value: string) => { this.info = value }) Text(this.info) }.width('100%') .borderStyle(BorderStyle.Solid) .borderWidth(2) .borderColor('#C75450') } .width('100%') .height('100%') } }
TextInput表单操作是一个非常重要的操作,基本上各种交互都需要用到它,所以需要我们多练习几次哦。