[英]How to preserve cursor position on textarea text change?
我正在嘗試實現一個textarea,它自動在React中插入緊密的parens,但每當我修改textarea的value屬性時,光標會跳轉到正在編輯的文本的末尾。
這是我的onChange函數:
//on change
function(event) {
var newText = event.target.value
var cursorPosition = getCursorPosition(event.target)
if(lastCharacterWasParen(newText, cursorPosition)){
newText = newText.slice(0, cursorPosition) + ')' + newText.slice(cursorPosition)
}
this.setProps({text: newText}})
}
這成功插入了paren,但如何保留光標位置?
我之前做過類似的事情。
更改光標位置的方法是使用: evt.target.selectionEnd
在您的情況下,您可以在插入之前記錄selectionEnd,插入之后,將selectionEnd設置為它應該的位置。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.