2016-08-03 60 views
2

我在editorState上做了一些棘手的狀態突變,我失去了選擇。在突變後失去選擇

我需要獲取currentText(),將其轉換爲帶有一些魔法庫的HTML並將其轉換回editorState。這工作正常,這只是選擇,打破如此艱難。

現在,我試圖在第一個開始獲取選擇,然後做一個forceSelection,但與selection.hasFocus()(這似乎並不真正相關...)的一些錯誤失敗。

我猜我需要計算基於錨點和偏移量的「新」選擇,但不是很確定,有什麼想法可以做到這一點?

現在我的代碼如下所示:

// onChangeHandler: 

const currentContentState = editorState.getCurrentContent() 
const selectionState = editorState.getSelection() 

const plainHtml = magicOperation(currentContentState.getPlainText()) 

const currentContentBlocks = convertFromHTML(plainHtml) 
const contentState = ContentState.createFromBlockArray(currentContentBlocks) 

const newEditorState = EditorState.createWithContent(contentState) 

this.setState({ 
    editorState: EditorState.forceSelection(
    newEditorState, 
    selectionState 
) 
}) 

是一個黑客,我知道我只是在玩弄DraftJS如果我能做到這一點,在我做的情況下,它工作順利我肯定會使用一個用於在editorState中添加HTML的裝飾器。

謝謝你的時間!

回答

3

selectionState包含塊密鑰(anchorKey & focusKey)。由於您替換了整個塊,所以鍵更改了。你需要做的是從偏移量中找到關鍵字,並將其設置爲新的selectionState,然後將其應用於新的editorState。

我很有趣,爲什麼你需要將純文本轉換爲html並設置回來。

+0

是的,我實現的實體而不是convertinfFromHTML,仍然需要計算選擇。對? – davesnx

+0

沒有。你需要設置selectionState的anchorKey和focusKey屬性。 –

+0

並將其與選擇合併? – davesnx

相關問題