@Entry
@Component
struct TextAreaExample {
@State inputTxt: string = '';
controller: TextAreaController = new TextAreaController();
back(): string | undefined {
if (this.inputTxt.length <= 0) {
return undefined;
} else {
return this.inputTxt.substring(0, this.inputTxt.length - 1);
}
}
build() {
Column() {
TextArea({
text: this.inputTxt,
placeholder: '请输入消息...',
controller: this.controller
})
.placeholderFont({ size: 16, weight: 400 })
.width(336)
.height(56)
.margin(20)
.fontSize(16)
.fontColor('#182431')
.backgroundColor('#FFFFFF')
.onChange((value: string) => {
if (value.length < this.inputTxt.length) {
let str = this.back();
if ((str == null) || (str == undefined)) {
this.inputTxt = '';
} else {
this.inputTxt = str;
}
} else {
this.inputTxt = value;
}
})
}.width('100%').height('100%').backgroundColor('#F1F3F5')
}
} 可以看到onChange回调函数中,对返回值value和之前的输入内容inputTxt做了判断比较。如果执行了删除操作,那么无论光标在什么位置,都会删除inputTxt末尾的字符并重新赋值。
TextAreaOptions.text没有进行双向绑定,且每次删除操作总是在onChange回调中删除被@State装饰的状态变量inputTxt末尾的字符并重新赋值,导致了光标无论处于什么位置,点击软键盘的删除按钮,光标都会跳转到最后并删除最后一个字符。
@Entry
@Component
struct TextAreaExample {
@State inputTxt: string = '无';
controller: TextAreaController = new TextAreaController();
build() {
Column() {
TextArea({
text: this.inputTxt,
placeholder: '请输入消息...',
controller: this.controller
})
.placeholderFont({ size: 16, weight: 400 })
.width(336)
.height(56)
.margin(20)
.fontSize(16)
.fontColor('#182431')
.backgroundColor('#FFFFFF')
.onChange((value: string) => {
this.inputTxt = value;
});
}.width('100%').height('100%').backgroundColor('#F1F3F5');
}
} @Entry
@Component
struct TextAreaExampleV2 {
@State inputTxt: string = '无';
controller: TextAreaController = new TextAreaController();
build() {
Column() {
TextArea({
text: $$this.inputTxt,
placeholder: '请输入消息...',
controller: this.controller
})
.placeholderFont({ size: 16, weight: 400 })
.width(336)
.height(56)
.margin(20)
.fontSize(16)
.fontColor('#182431')
.backgroundColor('#FFFFFF');
}.width('100%').height('100%').backgroundColor('#F1F3F5');
}
}