• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 文本输入 (TextInput/TextArea)
2
3
4TextInput、TextArea是输入框组件,通常用于响应用户的输入操作,比如评论区的输入、聊天框的输入、表格的输入等,也可以结合其它组件构建功能页面,例如登录注册页面。具体用法请参考[TextInput](../reference/apis-arkui/arkui-ts/ts-basic-components-textinput.md)、[TextArea](../reference/apis-arkui/arkui-ts/ts-basic-components-textarea.md)。
5
6
7## 创建输入框
8
9TextInput为单行输入框、TextArea为多行输入框。通过以下接口来创建。
10
11```ts
12TextInput(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: TextInputController})
13```
14
15```ts
16TextArea(value?:{placeholder?: ResourceStr, text?: ResourceStr, controller?: TextAreaController})
17```
18
19- 单行输入框
20
21  ```ts
22  TextInput()
23  ```
24
25  ![zh-cn_image_0000001511580844](figures/zh-cn_image_0000001511580844.png)
26
27
28- 多行输入框
29
30  ```ts
31  TextArea()
32  ```
33
34  ![zh-cn_image_0000001562940481](figures/zh-cn_image_0000001562940481.png)
35
36  多行输入框文字超出一行时会自动折行。
37
38
39  ```ts
40  TextArea({ text: "我是TextArea我是TextArea我是TextArea我是TextArea" }).width(300)
41  ```
42
43  ![zh-cn_image_0000001511580836](figures/zh-cn_image_0000001511580836.png)
44
45
46## 设置输入框类型
47
48TextInput有以下类型可选择:Normal基本输入模式、Password密码输入模式、Email邮箱地址输入模式、Number纯数字输入模式、PhoneNumber电话号码输入模式、USER_NAME用户名输入模式、NEW_PASSWORD新密码输入模式、NUMBER_PASSWORD纯数字密码输入模式、<!--Del-->SCREEN_LOCK_PASSWORD锁屏应用密码输入模式、<!--DelEnd-->NUMBER_DECIMAL带小数点的数字输入模式、带URL的输入模式。通过type属性进行设置:
49
50
51- 基本输入模式(默认类型)
52
53  ```ts
54  TextInput()
55    .type(InputType.Normal)
56  ```
57
58  ![zh-cn_image_0000001562820765](figures/zh-cn_image_0000001562820765.png)
59
60- 密码输入模式
61
62  ```ts
63  TextInput()
64    .type(InputType.Password)
65  ```
66
67  ![zh-cn_image_0000001511580840](figures/zh-cn_image_0000001511580840.png)
68
69- 邮箱地址输入模式
70
71  ```ts
72  TextInput()
73    .type(InputType.Email)
74  ```
75
76  ![text_input_type_email](figures/text_input_type_email.PNG)
77
78- 纯数字输入模式
79
80  ```ts
81  TextInput()
82    .type(InputType.Number)
83  ```
84
85  ![text_input_type_number](figures/text_input_type_number.PNG)
86
87- 电话号码输入模式
88
89  ```ts
90  TextInput()
91    .type(InputType.PhoneNumber)
92  ```
93
94  ![text_input_type_phone_number](figures/text_input_type_phone_number.PNG)
95
96- 带小数点的数字输入模式
97
98  ```ts
99  TextInput()
100    .type(InputType.NUMBER_DECIMAL)
101  ```
102
103  ![text_input_type_number_decimal](figures/text_input_type_number_decimal.PNG)
104
105- 带URL的输入模式
106
107  ```ts
108  TextInput()
109    .type(InputType.URL)
110  ```
111
112  ![text_input_type_url](figures/text_input_type_url.PNG)
113
114## 自定义样式
115
116- 设置无输入时的提示文本。
117
118
119  ```ts
120  TextInput({ placeholder: '我是提示文本' })
121  ```
122
123  ![zh-cn_image_0000001511900400](figures/zh-cn_image_0000001511900400.png)
124
125
126- 设置输入框当前的文本内容。
127
128  ```ts
129  TextInput({ placeholder: '我是提示文本', text: '我是当前文本内容' })
130  ```
131
132  ![zh-cn_image_0000001562820761](figures/zh-cn_image_0000001562820761.png)
133
134- 添加backgroundColor改变输入框的背景颜色。
135
136  ```ts
137  TextInput({ placeholder: '我是提示文本', text: '我是当前文本内容' })
138    .backgroundColor(Color.Pink)
139  ```
140
141  ![zh-cn_image_0000001511740444](figures/zh-cn_image_0000001511740444.png)
142
143  更丰富的样式可以结合[通用属性](../reference/apis-arkui/arkui-ts/ts-component-general-attributes.md)实现。
144
145
146## 添加事件
147
148文本框主要用于获取用户输入的信息,把信息处理成数据进行上传,绑定onChange事件可以获取输入框内改变的内容。用户也可以使用通用事件来进行相应的交互操作。
149
150```ts
151TextInput()
152  .onChange((value: string) => {
153    console.info(value);
154  })
155  .onFocus(() => {
156    console.info('获取焦点');
157  })
158```
159
160## 场景示例
161
162在登录/注册页面,用户进行登录或注册。
163
164```ts
165@Entry
166@Component
167struct TextInputSample {
168  build() {
169    Column() {
170      TextInput({ placeholder: 'input your username' }).margin({ top: 20 })
171        .onSubmit((EnterKeyType) => {
172          console.info(EnterKeyType + '输入法回车键的类型值');
173        })
174      TextInput({ placeholder: 'input your password' }).type(InputType.Password).margin({ top: 20 })
175        .onSubmit((EnterKeyType) => {
176          console.info(EnterKeyType + '输入法回车键的类型值');
177        })
178      Button('Sign in').width(150).margin({ top: 20 })
179    }.padding(20)
180  }
181}
182```
183
184![textinput](figures/textinput.gif)
185
186## 键盘避让
187
188键盘抬起后,具有滚动能力的容器组件在横竖屏切换时,才会生效键盘避让,若希望无滚动能力的容器组件也生效键盘避让,建议在组件外嵌套一层具有滚动能力的容器组件,比如[Scroll](../reference/apis-arkui/arkui-ts/ts-container-scroll.md)、[List](../reference/apis-arkui/arkui-ts/ts-container-list.md)、[Grid](../reference/apis-arkui/arkui-ts/ts-container-grid.md)。
189
190```ts
191// xxx.ets
192@Entry
193@Component
194struct Index {
195  placeHolderArr: string[] = ['1', '2', '3', '4', '5', '6', '7'];
196
197  build() {
198    Scroll() {
199      Column() {
200        ForEach(this.placeHolderArr, (placeholder: string) => {
201          TextInput({ placeholder: 'TextInput ' + placeholder })
202            .margin(30)
203        })
204      }
205    }
206    .height('100%')
207    .width('100%')
208  }
209}
210```
211
212![textinputkeyboardavoid](figures/TextInputKeyboardAvoid.gif)
213
214## 光标避让
215
216[keyBoardAvoidMode](../reference/apis-arkui/js-apis-arkui-UIContext.md#keyboardavoidmode11)枚举中的OFFSET和RESIZE在键盘抬起后,不支持二次避让。如果想要支持光标位置在点击或者通过接口设置变化后发生二次避让,可以考虑使用OFFSET_WITH_CARET和RESIZE_CARET替换原有的OFFSET和RESIZE模式。<br>
217对于滚动容器更推荐使用RESIZE_WITH_CARET,非滚动容器应该使用OFFSET_WITH_CARET。
218
219```ts
220// EntryAbility.ets
221import { KeyboardAvoidMode } from '@kit.ArkUI';
222
223// Used in UIAbility
224onWindowStageCreate(windowStage: window.WindowStage) {
225  // Main window is created, set main page for this ability
226  hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
227
228  windowStage.loadContent('pages/Index', (err, data) => {
229    let keyboardAvoidMode = windowStage.getMainWindowSync().getUIContext().getKeyboardAvoidMode();
230  windowStage.getMainWindowSync().getUIContext().setKeyboardAvoidMode(KeyboardAvoidMode.OFFSET_WITH_CARET);
231    if (err.code) {
232      hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
233      return;
234    }
235    hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? '');
236  });
237}
238```
239
240```ts
241// xxx.ets
242@Entry
243@Component
244struct Index {
245  @State caretPosition: number = 600;
246  areaController: TextAreaController = new TextAreaController();
247  text = "Most of us compare ourselves with anyone we think is happier — a relative, someone we know a lot, or someone we hardly know. As a result, what we do remember is anything that makes others happy, anything that makes ourselves unhappy, totally forgetting that there is something happy in our own life.\
248  So the best way to destroy happiness is to look at something and focus on even the smallest flaw. It is the smallest flaw that would make us complain. And it is the complaint that leads to us becoming unhappy.\
249  If one chooses to be happy, he will be blessed; if he chooses to be unhappy, he will be cursed. Happiness is just what you think will make you happy.Most of us compare ourselves with anyone we think is happier — a relative, someone we know a lot, or someone we hardly know. As a result, what we do remember is anything that makes others happy, anything that makes ourselves unhappy, totally forgetting that there is something happy in our own life.\
250  So the best way to destroy happiness is to look at something and focus on even the smallest flaw. It is the smallest flaw that would make us complain. And it is the complaint that leads to us becoming unhappy.\
251  If one chooses to be happy, he will be blessed; if he chooses to be unhappy, he will be cursed. Happiness is just what you think will make you happy.Most of us compare ourselves with anyone we think is happier — a relative, someone we know a lot, or someone we hardly know. As a result, what we do remember is anything that makes others happy, anything that makes ourselves unhappy, totally forgetting that there is something happy in our own life.\
252  So the best way to destroy happiness is to look at something and focus on even the smallest flaw. It is the smallest flaw that would make us complain. And it is the complaint that leads to us becoming unhappy.\
253  If one chooses to be happy, he will be blessed; if he chooses to be unhappy, he will be cursed. Happiness is just what you think will make you happy.Most of us compare ourselves with anyone we think is happier — a relative, someone we know a lot, or someone we hardly know. As a result, what we do remember is anything that makes others happy, anything that makes ourselves unhappy, totally forgetting that there is something happy in our own life.\
254  So the best way to destroy happiness is to look at something and focus on even the smallest flaw. It is the smallest flaw that would make us complain. And it is the complaint that leads to us becoming unhappy.\
255  If one chooses to be happy, he will be blessed; if he chooses to be unhappy, he will be cursed. Happiness is just what you think will make you happy.Most of us compare ourselves with anyone we think is happier — a relative, someone we know a lot, or someone we hardly know. As a result, what we do remember is anything that makes others happy, anything that makes ourselves unhappy, totally forgetting that there is something happy in our own life.\
256  ";
257
258  build() {
259    Scroll() {
260      Column() {
261        Row() {
262          Button('CaretPostiion++: ' + this.caretPosition).onClick(() => {
263            this.caretPosition += 1;
264          }).fontSize(10)
265          Button('CaretPostiion--: ' + this.caretPosition).onClick(() => {
266            this.caretPosition -= 1;
267          }).fontSize(10)
268          Button('SetCaretPostion: ').onClick(() => {
269            this.areaController.caretPosition(this.caretPosition);
270          }).fontSize(10)
271        }
272
273        TextArea({ text: this.text, controller: this.areaController })
274          .width('100%')
275          .fontSize('20fp')
276      }
277    }.width('100%').height('100%')
278  }
279}
280```
281
282![textinputkeyboardavoid](figures/caretavoid.gif)
283
284## 相关实例
285
286针对文本输入开发,有以下相关实例可供参考:
287
288- [简易计算器(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SimpleCalculator)