0

我需要将焦点应用到 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)
  });
}
4

2 回答 2

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

然后用它来移动焦点:

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

现在可以像这样使用它:

this.setState({ editorState: moveFocusToStart(editorState) })
于 2016-11-08T15:04:44.627 回答
0

我认为您也可以使用merge, 来设置焦点和锚点偏移,如下所示:

function moveFocusToStart(editorState: EditorState): EditorState {
  const selectionState = editorState.getSelection();
  return EditorState.forceSelection(
    editorState,
    selectionState.merge({
      anchorOffset: 0,
      focusOffset: 0,
    }),
  );
}
于 2021-09-20T21:57:56.707 回答