【问题标题】:Losing the selection after a mutation突变后失去选择
【发布时间】:2016-08-03 16:51:25
【问题描述】:

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

是一个 hack,我知道我只是在玩 DraftJS 如果我能做到这一点,如果我让它顺利运行,我肯定会使用装饰器在 editorState 中添加 HTML。

感谢您的宝贵时间!

【问题讨论】:

    标签: reactjs draftjs


    【解决方案1】:

    selectionState 包含块键(anchorKey&focusKey)。由于您替换了整个块,因此键发生了变化。您需要做的是从偏移量中找到键并将其设置为新的 selectionState,然后再将其应用于新的 editorState。

    我很有趣为什么您需要将纯文本转换为 html 并返回。

    【讨论】:

    • 是的,我正在实现实体而不是 convertinfFromHTML 并且仍然需要计算选择。对吗?
    • 没有。您需要设置 selectionState 的 anchorKey 和 focusKey 属性。
    • 并将其与所选内容合并?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多