【问题标题】:Insert text at cursor position in React在 React 中的光标位置插入文本
【发布时间】:2019-03-25 02:30:52
【问题描述】:

我有一个文本区域,当用户单击按钮时,我想在光标位置插入文本。有谁知道该怎么做?

【问题讨论】:

  • 当您单击按钮时,您会移动焦点元素,因此文本中不再有光标。因此,您必须跟踪光标的最后一个位置,然后将文本区域的值设置为当前值 + 最后一个已知光标位置处的额外文本。

标签: reactjs


【解决方案1】:

Qwertie 当然是对的。 无论如何,如果您想将给定的字符串插入光标位置的文本区域 你可以使用这样的函数:

 insertMyText = e => {
      let textToInsert = " this is the inserted text "
      let cursorPosition = e.target.selectionStart
      let textBeforeCursorPosition = e.target.value.substring(0, cursorPosition)
      let textAfterCursorPosition = e.target.value.substring(cursorPosition, e.target.value.length)
      e.target.value = textBeforeCursorPosition + textToInsert + textAfterCursorPosition
    }

和:

<textarea onClick={this.insertMyText}>bla bla bla bla</textarea>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-09
    • 2013-08-03
    • 2016-08-01
    • 1970-01-01
    相关资源
    最近更新 更多