ts-basic-components-textinput.md 12.3 KB
Newer Older
Z
zengyawen 已提交
1
# TextInput
Z
zengyawen 已提交
2

E
ester.zhou 已提交
3
The **\<TextInput>** component provides single-line text input.
4

E
ester.zhou 已提交
5
>  **NOTE**
E
ester.zhou 已提交
6
>
E
ester.zhou 已提交
7
>  This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
Z
zengyawen 已提交
8

Z
zengyawen 已提交
9 10

## Child Components
Z
zengyawen 已提交
11

E
ester.zhou 已提交
12
Not supported
Z
zengyawen 已提交
13

Z
zengyawen 已提交
14 15 16

## APIs

E
ester.zhou 已提交
17
TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: TextInputController})
Z
zengyawen 已提交
18

E
ester.zhou 已提交
19 20 21 22
**Parameters**

| Name                    | Type                                    | Mandatory  | Description           |
| ----------------------- | ---------------------------------------- | ---- | --------------- |
E
ester.zhou 已提交
23
| placeholder   | [ResourceStr](ts-types.md#resourcestr)       | No   | Placeholder text displayed when there is no input.     |
E
ester.zhou 已提交
24
| text          | [ResourceStr](ts-types.md#resourcestr)       | No   | Current text input.<br>If the component has [stateStyles](ts-universal-attributes-polymorphic-style.md) or any other attribute that may trigger updating configured, you are advised to bind the state variable to the text in real time through the **onChange** event, so as to prevent display errors when the component is updated.<br>Since API version 10, this parameter supports [$$](../../quick-start/arkts-two-way-sync.md) for two-way binding of variables. |
E
ester.zhou 已提交
25
| controller<sup>8+</sup> | [TextInputController](#textinputcontroller8) | No   | Text input controller.|
Z
zengyawen 已提交
26 27 28 29


## Attributes

E
ester.zhou 已提交
30
Among the [universal attributes](ts-universal-attributes-size.md) and [universal text attributes](ts-universal-attributes-text-style.md), **fontColor**, **fontSize**, **fontStyle**, **fontWeight**, and **fontFamily** are supported. In addition, the following attributes are supported.
E
ester.zhou 已提交
31 32 33

| Name                      | Type                                    | Description                                      |
| ------------------------ | ---------------------------------------- | ---------------------------------------- |
34
| type                     | [InputType](#inputtype)     | Input box type.<br>Default value: **InputType.Normal**       |
E
ester.zhou 已提交
35
| placeholderColor         | [ResourceColor](ts-types.md#resourcecolor)     | Placeholder text color.<br>The default value follows the theme.  |
E
ester.zhou 已提交
36
| placeholderFont          | [Font](ts-types.md#font) | Placeholder text font.|
E
ester.zhou 已提交
37
| enterKeyType             | [EnterKeyType](#enterkeytype) | Type of the Enter key. Currently, only the default value is supported.<br>Default value: **EnterKeyType.Done**|
E
ester.zhou 已提交
38
| caretColor               | [ResourceColor](ts-types.md#resourcecolor)    | Color of the caret in the text box.<br>Default value: **'#007DFF'**                               |
E
ester.zhou 已提交
39
| maxLength                | number                                   | Maximum number of characters in the text input.                           |
E
ester.zhou 已提交
40
| inputFilter<sup>8+</sup> | {<br>value: [ResourceStr](ts-types.md#resourcestr),<br>error?: (value: string) =&gt; void<br>} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The regular expression can match single characters, but not strings.<br>- **value**: regular expression to set.<br>- **error**: filtered-out content to return when regular expression matching fails.|
E
ester.zhou 已提交
41 42 43 44
| copyOption<sup>9+</sup>  | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.<br>Default value: **CopyOptions.LocalDevice**<br>If this attribute is set to **CopyOptions.None**, the paste operation is allowed, but not the copy or cut operation.|
| showPasswordIcon<sup>9+</sup> | boolean | Whether to display the password icon at the end of the password text box.<br>Default value: **true**|
| style<sup>9+</sup> | [TextInputStyle](#textinputstyle9) \| [TextContentStyle](ts-appendix-enums.md#textcontentstyle10) | Text input style.<br>Default value: **TextInputStyle.Default**|
| textAlign<sup>9+</sup>   | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment of the text.<br>Default value: **TextAlign.Start**<br>**NOTE**<br>Available options are **TextAlign.Start**, **TextAlign.Center**, and **TextAlign.End**.<br>To set vertical alignment for the text, use the [align](ts-universal-attributes-location.md) attribute. The **align** attribute alone does not control the horizontal position of the text. In other words, **Alignment.TopStart**, **Alignment.Top**, and **Alignment.TopEnd** produce the same effect, top-aligning the text; **Alignment.Start**, **Alignment.Center**, and **Alignment.End** produce the same effect, centered-aligning the text vertically; **Alignment.BottomStart**, **Alignment.Bottom**, and **Alignment.BottomEnd** produce the same effect, bottom-aligning the text. |
E
ester.zhou 已提交
45
| selectedBackgroundColor<sup>10+</sup> | [ResourceColor](ts-types.md#resourcecolor) | Background color of the selected text.<br>If the opacity is not set, the color is opaque. For example, **0x80000000** indicates black with 50% opacity.|
E
ester.zhou 已提交
46
| caretStyle<sup>10+</sup> | {<br>width: [Length](ts-types.md#length)<br>} | Caret style.                                       |
E
ester.zhou 已提交
47
| caretPosition<sup>10+</sup> | number | Caret position.|
E
ester.zhou 已提交
48 49 50 51 52
| showUnit<sup>10+</sup>                |  [CustomBuilder](ts-types.md#CustomBuilder8)         | Unit for content in the component.<br>By default, there is no unit.|
| showError<sup>10+</sup> | string \| undefined | Error text displayed when an error occurs.<br>By default, no error text is displayed.|
| showUnderline<sup>10+</sup> | boolean | Whether to show an underline.<br>Default value: **false**|
| passwordIcon<sup>10+</sup> | [PasswordIcon](#passwordicon10) | Password icon to display at the end of the password text box.<br>By default, the system-provided icon is used.|
| enableKeyboardOnFocus<sup>10+</sup> | boolean | Whether to enable the input method when the component obtains focus.<br>Default value: **true**  |
E
ester.zhou 已提交
53 54 55

>  **NOTE**
>
E
ester.zhou 已提交
56
>  The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows: { top: 8 vp, right: 16 vp, bottom: 8 vp, left: 16 vp }
E
ester.zhou 已提交
57 58 59 60 61 62 63 64 65 66 67

## EnterKeyType

| Name                 | Description       |
| ------------------- | --------- |
| Go     | The Enter key is labeled "Go."  |
| Search | The Enter key is labeled "Search." |
| Send   | The Enter key is labeled "Send." |
| Next   | The Enter key is labeled "Next."|
| Done   | The Enter key is labeled "Done."    |

E
ester.zhou 已提交
68
## InputType
E
ester.zhou 已提交
69 70 71 72

| Name                | Description           |
| ------------------ | ------------- |
| Normal   | Normal input mode.<br>The value can contain digits, letters, underscores (_), spaces, and special characters.|
E
ester.zhou 已提交
73 74
| Password | Password input mode. The value can contain digits, letters, underscores (_), spaces, and special characters. An eye icon is used to show or hide the password, and the password is hidden behind dots by default.|
| Email    | Email address input mode. The value can contain digits, letters, underscores (_), and at signs (@). Only one at sign (@) is allowed.|
E
ester.zhou 已提交
75 76 77
| Number   | Digit input mode.     |
| PhoneNumber<sup>9+</sup> | Phone number input mode.<br>The value can contain digits, plus signs (+), hyphens (-), asterisks (*), and number signs (#). The length is not limited.|

E
ester.zhou 已提交
78
## TextInputStyle<sup>9+</sup>
E
ester.zhou 已提交
79 80 81

| Name                | Description           |
| ------------------ | ------------- |
E
ester.zhou 已提交
82 83
| Default   | Default style. The caret width is fixed at 1.5 vp, and the caret height is subject to the background height and font size of the selected text.  |
| Inline    | Inline input style. The background height of the selected text is the same as the height of the text box.     |
E
ester.zhou 已提交
84

E
ester.zhou 已提交
85 86 87 88 89 90 91
## PasswordIcon<sup>10+</sup>

| Name      | Type                                              | Mandatory| Description                                              |
| ---------- | -------------------------------------------------- | ---- | -------------------------------------------------- |
| onIconSrc  | string \|[Resource](ts-types.md#resource)| No  | Icon that can be used to hide the password in password input mode.|
| offIconSrc | string \|[Resource](ts-types.md#resource)| No  | Icon that can be used to show the password in password input mode.|

E
ester.zhou 已提交
92
## Events
E
ester.zhou 已提交
93

E
ester.zhou 已提交
94 95
In addition to the [universal events](ts-universal-events-click.md), the following events are supported.

E
ester.zhou 已提交
96
| Name                                                        | Description                                                    |
97
| ------------------------------------------------------------ | ------------------------------------------------------------ |
E
ester.zhou 已提交
98 99 100 101 102 103 104
| onChange(callback: (value: string) =&gt; void) | Triggered when the input changes.<br>**value**: text content.<br>This event is triggered when any of the following conditions is met:<br>1. Keyboard input is received.<br>2. Paste and cut is performed.<br>3. Ctrl+V is pressed.|
| onSubmit(callback: (enterKey: EnterKeyType) =&gt; void) | Triggered when the Enter key on the keyboard is pressed. The return value is the current type of the Enter key.<br>**enterKeyType**: type of the Enter key. For details, see [EnterKeyType](#enterkeytype).|
| onEditChanged(callback: (isEditing: boolean) =&gt; void)<sup>(deprecated)</sup> | Triggered when the input status changes. Since API version 8, **onEditChange** is recommended.|
| onEditChange(callback: (isEditing: boolean) =&gt; void)<sup>8+</sup> | Triggered when the input status changes. When the cursor is placed in the text box, it is in the editing state. Otherwise, it is in the non-editing state. If the value of **isEditing** is **true**, text input is in progress.|
| onCopy(callback:(value: string) =&gt; void)<sup>8+</sup> | Triggered when the copy button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be copied.|
| onCut(callback:(value: string) =&gt; void)<sup>8+</sup> | Triggered when the cut button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be cut.|
| onPaste(callback:(value: string) =&gt; void)<sup>8+</sup> | Triggered when the paste button on the pasteboard, which displays when the text box is long pressed, is clicked.<br>**value**: text to be pasted.|
E
ester.zhou 已提交
105 106

## TextInputController<sup>8+</sup>
E
ester.zhou 已提交
107

E
ester.zhou 已提交
108
Implements the controller of the **\<TextInput>** component.
Z
zengyawen 已提交
109

E
ester.zhou 已提交
110
### Objects to Import
Z
zengyawen 已提交
111 112 113
```
controller: TextInputController = new TextInputController()
```
114
### caretPosition<sup>8+</sup>
Z
zengyawen 已提交
115 116 117

caretPosition(value: number): void

E
ester.zhou 已提交
118
Sets the position of the caret.
Z
zengyawen 已提交
119

E
ester.zhou 已提交
120
**Parameters**
Z
zengyawen 已提交
121

E
ester.zhou 已提交
122 123 124
| Name| Type| Mandatory| Description                              |
| ------ | -------- | ---- | -------------------------------------- |
| value  | number   | Yes  | Length from the start of the string to the position where the caret is located.|
E
ester.zhou 已提交
125 126 127 128 129 130 131
### setTextSelection<sup>10+</sup>

setTextSelection(selectionStart: number, selectionStart: number): void

Sets the text selection area, which will be highlighted.

**Parameters**
Z
zengyawen 已提交
132

E
ester.zhou 已提交
133 134 135 136
| Name        | Type| Mandatory| Description              |
| -------------- | -------- | ---- | ---------------------- |
| selectionStart | number   | Yes  | Start position of the text selection area. The start position of the text in the text box is 0.|
| selectionEnd   | number   | Yes  | End position of the text selection area.|
E
ester.zhou 已提交
137

Z
zengyawen 已提交
138 139
## Example

E
ester.zhou 已提交
140 141
```ts
// xxx.ets
Z
zengyawen 已提交
142 143
@Entry
@Component
E
ester.zhou 已提交
144
struct TextInputExample {
Z
zengyawen 已提交
145
  @State text: string = ''
E
ester.zhou 已提交
146
  controller: TextInputController = new TextInputController()
Z
zengyawen 已提交
147 148 149

  build() {
    Column() {
E
ester.zhou 已提交
150
      TextInput({ text: this.text, placeholder: 'input your word...', controller: this.controller })
E
ester.zhou 已提交
151 152
        .placeholderColor(Color.Grey)
        .placeholderFont({ size: 14, weight: 400 })
Z
zengyawen 已提交
153
        .caretColor(Color.Blue)
E
ester.zhou 已提交
154 155 156 157 158
        .width(400)
        .height(40)
        .margin(20)
        .fontSize(14)
        .fontColor(Color.Black)
E
ester.zhou 已提交
159 160 161
        .inputFilter('[a-z]', (e) => {
          console.log(JSON.stringify(e))
        })
Z
zengyawen 已提交
162 163 164
        .onChange((value: string) => {
          this.text = value
        })
E
ester.zhou 已提交
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187
      Text(this.text)
      Button('Set caretPosition 1')
        .margin(15)
        .onClick(() => {
          // Move the caret to after the first entered character.
          this.controller.caretPosition(1)
        })
      // Password text box.
      TextInput({ placeholder: 'input your password...' })
        .width(400)
        .height(40)
        .margin(20)
        .type(InputType.Password)
        .maxLength(9)
        .showPasswordIcon(true)
      // Inline-style text box.
      TextInput({ placeholder: 'inline style' })
        .width(400)
        .height(50)
        .margin(20)
        .borderRadius(0)
        .style(TextInputStyle.Inline)
    }.width('100%')
Z
zengyawen 已提交
188 189 190 191
  }
}
```

E
ester.zhou 已提交
192
![textInput](figures/textInput.gif)