I'm doing some tricky state mutations on editorState and I'm losing the selection.
I need to get the currentText(), transform into HTML with some magic library and convert it back to editorState. That works fine, it's just the selection that breaks so hard.
Right now, I'm trying to get the selection on the first beginning and then do a forceSelection
, but fails with some error related to selection.hasFocus()
(that seems not really related...).
I'm guessing that I need to calculate the "new" selection based on anchors and offsets, but not really sure, any ideas to do that?
Right now my code looks like:
// 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
)
})
Is a hack, I know I'm just playing around DraftJS If I can achieve that, in the case that I make it work smooth I would definitely use a Decorator for add HTML inside the editorState.
Thanks for your time!
The selectionState contains block keys (anchorKey&focusKey). The keys changed because you replace the whole blocks. What you need to do is find the keys from the offset and set it to your new selectionState before apply it to your new editorState.
I'm interesting why you need convert plain text to html and set back.
来源:https://stackoverflow.com/questions/38749474/losing-the-selection-after-a-mutation