焦点编辑器,将光标定位在第一个块的开头

can*_*era 0 reactjs draftjs

我需要将焦点应用于 Draft.js 编辑器并将光标定位在第一行/块的开头。编辑器包含多行/块。

this.refs.editor.focus()应用时,光标始终位于编辑器内第二个块/行的开头。

使用这个问题这个问题作为指导,我尝试了下面的代码但没有成功。我怀疑传递blockMapcreateFromBlockArray()不正确:

focusTopLine() {

  this.refs.editor.focus();

  const { editorState } = this.state;
  const contentState = editorState.getCurrentContent();
  const selectionState = editorState.getSelection();
  const blockMap = contentState.getBlockMap();

  const newContentState = ContentState.createFromBlockArray(blockMap);
  const newEditorState = EditorState.createWithContent(newContentState);

  this.setState({
    editorState: EditorState.forceSelection(newEditorState, selectionState)
  });
}
Run Code Online (Sandbox Code Playgroud)

tob*_*sen 5

您可以(可能,我还没有测试过)执行类似于EditorState.moveFocusToEnd()实现方式的操作:

首先,EditorState在选择第一个块的位置创建一个新块:

function moveSelectionToStart(editorState) {
  const content = editorState.getCurrentContent()
  const firstBlock = content.getFirstBlock()
  const firstKey = firstBlock.getKey()
  const length = firstBlock.getLength()

  return EditorState.acceptSelection(
    editorState,
    new SelectionState({
      anchorKey: firstKey,
      anchorOffset: length,
      focusKey: firstKey,
      focusOffset: length,
      isBackward: false,
    })
  )
}
Run Code Online (Sandbox Code Playgroud)

然后用它来移动焦点:

function moveFocusToStart(editorState) {
  const afterSelectionMove = EditorState.moveSelectionToStart(editorState)
  return EditorState.forceSelection(
    afterSelectionMove,
    afterSelectionMove.getSelection()
  )
}
Run Code Online (Sandbox Code Playgroud)

现在可以这样使用:

this.setState({ editorState: moveFocusToStart(editorState) })
Run Code Online (Sandbox Code Playgroud)