ts-basic-components-textarea.md 12.2 KB
Newer Older
Z
zengyawen 已提交
1
# TextArea
Z
zengyawen 已提交
2

E
ester.zhou 已提交
3
The **\<TextArea>** component provides multi-line text input and automatically wraps text so that each line does not have more than the width of the component.
Z
zengyawen 已提交
4

E
esterzhou 已提交
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

E
esterzhou 已提交
10
## Child Components
Z
zengyawen 已提交
11

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

Z
zengyawen 已提交
14 15 16

## APIs

E
esterzhou 已提交
17
TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: TextAreaController})
Z
zengyawen 已提交
18

E
ester.zhou 已提交
19
**Parameters**
Z
zengyawen 已提交
20

E
ester.zhou 已提交
21 22
| Name                    | Type                                    | Mandatory  | Description          |
| ----------------------- | ---------------------------------------- | ---- | -------------- |
E
ester.zhou 已提交
23 24
| placeholder      | [ResourceStr](ts-types.md#resourcestr)  | No   | Text displayed when there is no input.<br>When only the **placeholder** attribute is set, the text selection handle is still available; the caret stays at the beginning of the placeholder text when the handle is released.    |
| 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,<br>so as to prevent display errors when the component is updated.<br>Since API version 10, this parameter supports two-way binding through [$$](../../quick-start/arkts-two-way-sync.md).|
E
ester.zhou 已提交
25
| controller<sup>8+</sup> | [TextAreaController](#textareacontroller8) | No   | Text area controller.|
Z
zengyawen 已提交
26 27


E
ester.zhou 已提交
28
## Attributes
Z
zengyawen 已提交
29

E
ester.zhou 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43
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.

| Name                     | Type                                                    | Description                                                        |
| ------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| placeholderColor          | [ResourceColor](ts-types.md#resourcecolor)                   | Placeholder text color.<br>The default value follows the theme.              |
| placeholderFont           | [Font](ts-types.md#font)                                     | Placeholder text style, including the font size, font width, font family, and font style. Currently, only the default font family is supported.|
| textAlign                 | [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.|
| caretColor                | [ResourceColor](ts-types.md#resourcecolor)                   | Color of the caret in the text box.<br>Default value: **'#007DFF'**                |
| inputFilter<sup>8+</sup>  | {<br>value: [ResourceStr](ts-types.md#resourcestr),<br>error?: (value: string) => void<br>} | Regular expression for input filtering. Only inputs that comply with the regular expression can be displayed. Other inputs are filtered out. The specified 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.|
| 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 the copy and cut operations are not.|
| maxLength<sup>10+</sup>   | number                                                       | Maximum number of characters in the text input.<br>By default, there is no maximum number of characters.|
| showCounter<sup>10+</sup> | boolean                                                      | Whether to show the number of entered characters when **maxLength** is set.<br>Default value: **false**  |
| style<sup>10+</sup>       | [TextContentStyle](ts-appendix-enums.md#textcontentstyle10)  | Style of the component.<br>Default value: **TextContentStyle.DEFAULT**   |
| enableKeyboardOnFocus<sup>10+</sup> | boolean | Whether to enable the input method when the component obtains focus.<br>Default value: **true**  |
E
ester.zhou 已提交
44
| selectionMenuHidden<sup>10+</sup> | boolean                                                      | Whether to display the text selection menu when the text box is long-pressed or right-clicked.<br>Default value: **false**|
E
ester.zhou 已提交
45

E
ester.zhou 已提交
46 47
>  **NOTE**
>
E
ester.zhou 已提交
48
>  The default value of the universal attribute [padding](ts-universal-attributes-size.md) is as follows: <br>{<br> top: 8 vp,<br> right: 16 vp,<br> bottom: 8 vp,<br> left: 16 vp<br> }
E
ester.zhou 已提交
49

Z
zengyawen 已提交
50 51
## Events

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

E
ester.zhou 已提交
54
| Name                                                        | Description                                                    |
E
ester.zhou 已提交
55
| ------------------------------------------------------------ | ------------------------------------------------------------ |
E
ester.zhou 已提交
56 57 58 59 60
| onChange(callback: (value: string) =&gt; void) | Triggered when the input in the text box changes.<br>- **value**: text entered.|
| onEditChange(callback: (isEditing: boolean) =&gt; void)<sup>10+</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<sup>8+</sup>(callback:(value: string) =&gt; void) | 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<sup>8+</sup>(callback:(value: string) =&gt; void) | 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<sup>8+</sup>(callback:(value: string) =&gt; void) | 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 已提交
61 62
| onTextSelectionChange(callback: (selectionStart: number, selectionEnd: number) => void)<sup>10+</sup> | Triggered when the text selection position changes.<br>**selectionStart**: start position of the text selection area. The start position of text in the text box is **0**.<br>**selectionEnd**: end position of the text selection area.|
| onContentScroll(callback: (totalOffsetX: number, totalOffsetY: number) => void)<sup>10+</sup> | Triggered when the text content is scrolled.<br>**totalOffsetX**: X coordinate offset of the text in the content area.<br>**totalOffsetY**: Y coordinate offset of the text in the content area.|
Z
zengyawen 已提交
63

E
ester.zhou 已提交
64 65
## TextAreaController<sup>8+</sup>

E
ester.zhou 已提交
66
Defines the controller for controlling the **\<TextArea>** component. Currently, the controller can be used to control the caret position.
E
ester.zhou 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79

### Objects to Import

```
controller: TextAreaController = new TextAreaController()
```

### caretPosition<sup>8+</sup>

caretPosition(value: number): void

Sets the position of the caret.

E
ester.zhou 已提交
80 81 82 83 84
**Parameters**

| 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 已提交
85

E
ester.zhou 已提交
86 87 88 89
### setTextSelection<sup>10+</sup>

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

E
ester.zhou 已提交
90
Sets the text selection range and highlights the selected text when the component is focused. This API works only when the value of **selectionStart** is less than that of **selectionEnd**.
E
ester.zhou 已提交
91 92 93

**Parameters**

E
ester.zhou 已提交
94 95 96 97
| Name        | Type| Mandatory| Description                                                    |
| -------------- | -------- | ---- | ------------------------------------------------------------ |
| selectionStart | number   | Yes  | Start position of the text selection range. The start position of text in the text box is 0.<br>A value less than 0 evaluates to the value **0**. A value greater than the maximum text length evaluates to the maximum text length.<br>|
| selectionEnd   | number   | Yes  | End position of the text selection range.<br>A value less than 0 evaluates to the value **0**. A value greater than the maximum text length evaluates to the maximum text length.<br>|
Z
zengyawen 已提交
98

E
ester.zhou 已提交
99 100 101 102 103 104
### stopEditing<sup>10+</sup>

stopEditing(): void

Exits the editing state.

E
ester.zhou 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
### getTextContentRect<sup>10+</sup>

getTextContentRect(): [RectResult](#rectresult10)

Obtains the position of the edited text area relative to the component and its size. The unit of the return value is pixel.

**Return value**

| Type      | Description      |
| -------------------  | -------- |
| [RectResult](#rectresult10) | Position of the edited text area relative to the component and its size.|

> **NOTE**
>
> - If no text is entered, the return value contains the position information, but the size is 0.
> - The position information is the offset of the first character relative to the editable area.
> - If there is input, the width in the return value is the fixed width of the editable area.

### RectResult<sup>10+</sup>

Describes the position and size.

| Parameter     | Type    | Description|
| ------- | ------ | ----------------------- |
| x     | number | X coordinate.|
| y     | number | Y coordinate.|
| width | number | Content width.|
| height | number | Content height.|


### getTextContentLineCount<sup>10+</sup>

getTextContentLineCount(): number

Obtains the number of lines of the edited text.

**Return value**

| Type | Description      |
| ----- | -------- |
| number| Number of lines of the edited text.|

Z
zengyawen 已提交
147 148
## Example

E
ester.zhou 已提交
149 150
### Example 1

E
ester.zhou 已提交
151 152
```ts
// xxx.ets
Z
zengyawen 已提交
153 154
@Entry
@Component
E
ester.zhou 已提交
155
struct TextAreaExample {
Z
zengyawen 已提交
156
  @State text: string = ''
E
ester.zhou 已提交
157 158
  controller: TextAreaController = new TextAreaController()

Z
zengyawen 已提交
159 160
  build() {
    Column() {
E
ester.zhou 已提交
161
      TextArea({
E
ester.zhou 已提交
162
        text: this.text,
E
ester.zhou 已提交
163 164 165 166 167 168
        placeholder: 'The text area can hold an unlimited amount of text. input your word...',
        controller: this.controller
      })
        .placeholderFont({ size: 16, weight: 400 })
        .width(336)
        .height(56)
E
ester.zhou 已提交
169
        .margin(20)
E
ester.zhou 已提交
170 171 172
        .fontSize(16)
        .fontColor('#182431')
        .backgroundColor('#FFFFFF')
Z
zengyawen 已提交
173 174 175
        .onChange((value: string) => {
          this.text = value
        })
E
ester.zhou 已提交
176 177
      Text(this.text)
      Button('Set caretPosition 1')
E
ester.zhou 已提交
178
        .backgroundColor('#007DFF')
E
ester.zhou 已提交
179 180 181 182 183
        .margin(15)
        .onClick(() => {
          // Move the caret to after the first entered character.
          this.controller.caretPosition(1)
        })
E
ester.zhou 已提交
184
    }.width('100%').height('100%').backgroundColor('#F1F3F5')
Z
zengyawen 已提交
185 186 187 188
  }
}
```

E
ester.zhou 已提交
189
![textArea](figures/textArea.gif)
E
ester.zhou 已提交
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227

### Example 2

```ts
// xxx.ets
@Entry
@Component
struct TextAreaExample {
  @State text: string = 'test'
  @State counterVisible: boolean = false
  @State maxNumber: number = -1
  controller: TextAreaController = new TextAreaController()

  build() {
    Column() {
      TextArea({
        text: this.text,
        placeholder: 'The text area can hold an unlimited amount of text. input your word...',
        controller: this.controller
      })
        .placeholderFont({ size: 16, weight: 400 })
        .width(336)
        .height(56)
        .margin(20)
        .fontSize(16)
        .fontColor('#182431')
        .maxLength(4)
        .showCounter(true)
        .backgroundColor('#FFFFFF')
        .onChange((value: string) => {
          this.text = value
        })
    }.width('100%').height('100%').backgroundColor('#F1F3F5')
  }
}
```

![maxLength](figures/maxLength.png)