Losing the selection after a mutation

萝らか妹 提交于 2019-12-31 02:34:26

问题


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!


回答1:


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!