我需要将焦点应用于Draft.js编辑器并将光标定位在第一行/块的开头。编辑器包含多行/块。
仅应用this.refs.editor.focus()
时,光标始终位于编辑器中第二个块/行的开头。
使用this question和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)
});
}
答案 0 :(得分:2)
您可以(可能,我还没有对此进行过测试)与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) })