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

Focus Editor, Position Cursor at Start of First Block

我需要将焦点应用到 Draft.js 编辑器并将光标定位在第一个 line/block 的开头。编辑器包含多个lines/blocks.

仅应用 this.refs.editor.focus(),光标始终位于编辑器中第二个 block/line 的开头。

使用 this question and this issue 作为指导,我尝试了下面的代码但没有成功。我怀疑将 blockMap 传递给 createFromBlockArray() 是不正确的:

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)
  });
}

您可以(可能,我还没有测试过)按照 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,
    })
  )
}

然后用它来移动焦点:

function moveFocusToStart(editorState) {
  const afterSelectionMove = EditorState.moveSelectionToStart(editorState)
  return EditorState.forceSelection(
    afterSelectionMove,
    afterSelectionMove.getSelection()
  )
}

现在可以这样使用了:

this.setState({ editorState: moveFocusToStart(editorState) })

我想你也可以使用 merge,像这样设置焦点和锚点偏移:

function moveFocusToStart(editorState: EditorState): EditorState {
  const selectionState = editorState.getSelection();
  return EditorState.forceSelection(
    editorState,
    selectionState.merge({
      anchorOffset: 0,
      focusOffset: 0,
    }),
  );
}