2016-11-08 56 views
0

我需要將焦點應用於Draft.js編輯器,並將光標定位在第一行/塊的起始位置。編輯器包含多行/塊。焦點編輯器,位於第一個塊起始處的位置光標

只應用this.refs.editor.focus(),光標始終位於編輯器中第二個塊/行的起始位置。

使用this questionthis issue作爲指南,我試了下面的代碼沒有成功。我懷疑,路過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) 
    }); 
} 

回答

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) }) 
+0

謝謝 - 確認您的代碼工作。出於某種原因,我不得不在'setTimeout(...,0)'中將調用封裝到'setState'中,但是修改後它似乎正在工作。再次感謝。 – cantera

相關問題