@Entry @Component struct TextAreaExample { @State text: string = ''; controller: TextAreaController = new TextAreaController(); @State maxLength: number = 0; build() { Column() { Button('点击添加文本') .onClick(() => { this.controller.addText('这是一段很长的文本这是一段很长的文本这是一段很长的文本这是一段很长的文本这是一段很长的文本这是一段很长的文本这是一段很长的文本这是一段很长的文本这是一段很长的文本这是一段很长的文本这是一段很长的文本这是一段很长的文本这是一段很长的文本'); // 设置TextArea获焦 focusControl.requestFocus('focus1'); }) TextArea({ text: this.text, placeholder: 'The text area can hold an unlimited amount of text. input your word...', controller: this.controller, }) .id('focus1') .placeholderFont({ size: 16, weight: 400 }) .width(336) .height(100) .margin(20) .fontSize(16) .fontColor('#182431') .backgroundColor('#FFFFFF') // 监听文本变化事件 .onChange((value: string) => { // 计算当前输入文本长度 let length: number = value.length; // 更新maxLength状态:记录当前输入内容的最大长度 if (this.maxLength < length) { this.maxLength = length; } // 更新text状态:保存最新输入内容 this.text = value; // 调用controller的caretPosition方法:将光标定位到文本末尾 this.controller.caretPosition(this.maxLength); }) }.width('100%').height('100%').backgroundColor('#F1F3F5') } }
效果预览:

@Entry @Component struct TextAreaPage { @State message: string = 'Hello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello World'; addMessage: string = 'Hello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello World'; controller: Scroller = new Scroller(); scrollToBottom() { this.controller.scrollEdge(Edge.Bottom);// 通过控制器滚动到容器底部 } build() { Column() { Scroll(this.controller) { TextArea({ text: this.message }) .width('100%') .constraintSize({ minHeight: 200 }) .onSizeChange(() => { this.scrollToBottom(); }) } .height(200) Button('button') .onClick(() => { this.message = this.message + this.addMessage; }) } .height('100%') .width('100%') } }
效果预览:
