突变后丢失选择 [英] Losing the selection after a mutation

查看:45
本文介绍了突变后丢失选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对 editorState 进行一些棘手的状态更改,但我失去了选择.

I'm doing some tricky state mutations on editorState and I'm losing the selection.

我需要获取 currentText(),使用一些魔法库将其转换为 HTML 并将其转换回 editorState.效果很好,只是选择太难了.

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.

现在,我正在尝试在第一个开头获取选择,然后执行 forceSelection,但由于一些与 selection.hasFocus() 相关的错误而失败(这似乎不是真的相关...).

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

是一个黑客,我知道我只是在玩 DraftJS 如果我能做到这一点,如果我让它工作顺利,我肯定会使用装饰器在 editorState 中添加 HTML.

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.

感谢您的时间!

推荐答案

selectionState 包含块键(anchorKey&focusKey).密钥更改是因为您替换了整个块.您需要做的是从偏移量中找到键并将其设置为新的 selectionState,然后再将其应用于新的 editorState.

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.

我很感兴趣为什么您需要将纯文本转换为 html 并返回.

I'm interesting why you need convert plain text to html and set back.

这篇关于突变后丢失选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆