DraftJS:如何通过编程方式将焦点(光标)移动到右边的某个字符?

时间:2018-03-14 09:06:00

标签: javascript draftjs

我在编辑器中插入一些文本:

_insertText(text) {
    const { editorState, onChange } = this.props
    const newContentState = Modifier.insertText(
      editorState.getCurrentContent(),
      editorState.getSelection(),
      text
    )

    const newState = EditorState.createWithContent(newContentState)
    onChange(EditorState.acceptSelection(newState, editorState.getSelection()))
  }

但插入后,光标停留在插入点的锚点位置。我想将它移动到插入文本的末尾,这样我就可以继续编辑而无需手动移动光标。

请帮忙。

1 个答案:

答案 0 :(得分:0)

已修复此

_insertText(text) {
    const { editorState, onChange } = this.props
    const newContentState = Modifier.insertText(
      editorState.getCurrentContent(),
      editorState.getSelection(),
      text
    )

    const newState = EditorState.createWithContent(newContentState)
    const nextOffSet = editorState.getSelection().getFocusOffset() + text.length

    const newSelection = editorState.getSelection().merge({
      focusOffset: nextOffSet,
      anchorOffset: nextOffSet
    })

    onChange(EditorState.acceptSelection(newState, newSelection))
  }

如果有更好的解决方案,请告诉我。