TextInput
根據組件名字,可以得知他是一個文本輸出框。
聲明代碼👇
TextInput({placeholder?:ResourceStr,text?:ResourceStr});
placeholder: 就是提示文本,跟網頁開發中的placeholder一樣的
text:輸入框當前的文本內容
特殊屬性:
type(inputType.xxx). 可以決定輸入框的類型,xxx的值有Normal、password(密碼,會加密)、Email(郵箱格式)、Number(純數字)等
注意: 只做約束,不做校驗。
輸入框可以使用事件來控制用戶的交互操作。?
測試
使用placeholder來控制未輸入時的提示信息
使用type控制輸入的類型,比如使用密碼?
?當然,我們也可以是對他設置基本樣式,比如背景色,寬度等
最重要的,我們可以通過事件來處理邏輯??
@Entry
@Component
struct Index {@State message: string = 'Hello World'build() {Row() {Column() {Image($r('app.media.hongmeng')).width(250)Text($r('app.string.width_label')).fontSize(30).fontWeight(FontWeight.Medium)TextInput({placeholder:'請輸入圖片寬度:'}).type(InputType.Password).width(300).backgroundColor("#ff0000").onChange(e=>{console.log(e)})}.width('100%')}.height('100%')}
}
?通過事件交互進行圖片寬度的改變
我們通過交互事件將用戶輸入的數字大小賦值給imageWidth變量,再將image組件的width變成響應式的變量來完成這一操作。不過在其中要注意類型的轉換。因為textinput的text屬性需要的是一個字符串類型的,但是imageWidth是一個數字類型的,所以在使用的時候要考慮類型的轉換。這里我使用了Number()和toString()強轉。與javascript的語法相似。
@Entry
@Component
struct Index {@State message: string = 'Hello World'@State imageWidth: number = 30build() {Row() {Column() {Image($r('app.media.hongmeng')).width(this.imageWidth)Text($r('app.string.width_label')).fontSize(30).fontWeight(FontWeight.Medium)TextInput({text:this.imageWidth.toString()}).type(InputType.Number).width(150).backgroundColor("#ff0000").onChange(e=>{this.imageWidth = Number(e)})}.width('100%')}.height('100%')}
}