DraftJS:返回后重置块类型

n9i*_*els 6 draftjs

我目前正在构建一个类似于 medium.com 上使用的编辑器。对于每个unstyled块,我渲染一个自定义组件,其中包含编辑按钮以更改该部分的块类型。

但是,例如,当我将部分更改为 aheader-one并点击返回按钮时,新块也是一个header-one块。我喜欢看到新块unstyled而不是前一个块的相同类型。

关于如何做到这一点的任何想法?

编辑

经过更多的搜索和尝试,我自己找到了解决方案!似乎最好的方法是在split-blockkeyCommand 被触发时插入一个新块。示例代码如下:

createEmptyBlock(editorState: Draft.EditorState) {
    const newBlock = new Draft.ContentBlock({
        key: Draft.genKey(),
        type: "unstyled",
        text: "",
        characterList: Immutable.List()
    })

    const contentState = editorState.getCurrentContent()
    const newBlockMap = contentState.getBlockMap().set(newBlock.getKey(), newBlock)

    return Draft.EditorState.push(
        editorState,
        Draft.ContentState
            .createFromBlockArray(newBlockMap.toArray())
            .set('selectionAfter', contentState.getSelectionAfter().merge({
                anchorKey: newBlock.getKey(),
                anchorOffset: 0,
                focusKey: newBlock.getKey(),
                focusOffset: 0,
                isBackward: false,
            })) as Draft.ContentState,
        "split-block"
    )
}
Run Code Online (Sandbox Code Playgroud)

vin*_*zee 0

经过更多的搜索和尝试,我自己找到了解决方案!看来最好的方法是在触发分割块 keyCommand 时插入一个新块。

例如:

createEmptyBlock(editorState: Draft.EditorState) {
    const newBlock = new Draft.ContentBlock({
        key: Draft.genKey(),
        type: "unstyled",
        text: "",
        characterList: Immutable.List()
    })

    const contentState = editorState.getCurrentContent()
    const newBlockMap = contentState.getBlockMap().set(newBlock.getKey(), newBlock)

    return Draft.EditorState.push(
        editorState,
        Draft.ContentState
            .createFromBlockArray(newBlockMap.toArray())
            .set('selectionAfter', contentState.getSelectionAfter().merge({
                anchorKey: newBlock.getKey(),
                anchorOffset: 0,
                focusKey: newBlock.getKey(),
                focusOffset: 0,
                isBackward: false,
            })) as Draft.ContentState,
        "split-block"
    )
}
Run Code Online (Sandbox Code Playgroud)

此答案作为对问题DraftJS: Reset blockType after return的编辑发布,由 OP n9iels在 CC BY-SA 3.0 下进行。