0

我正在开发一个自定义的 draft.js 插件,该插件在其中插入一个带有 GIF 的原子块。我首先复制Draft.js 图像插件,因为它几乎相同。我的插件可以正常工作,但有一个问题我不确定如何最好地解决。

显示 Draft.js 交互错误的 Gif

要插入 GIF,我将按照 Image Plugin 中的示例addImage Modifier进行操作。但是,这总是在当前选择之后创建一个新的原子块。如果当前块是空的,我想把 GIF 放在那里。

这是我的修饰符函数的样子:

const addGiphy = (editorState, giphyId) => {
    const contentState = editorState.getCurrentContent();

    // This creates the new Giphy entity
    const contentStateWithEntity = contentState.createEntity("GIPHY", "IMMUTABLE", {
        giphyId
    });

    const entityKey = contentStateWithEntity.getLastCreatedEntityKey();

    // Work out where the selection is
    const currentSelection = editorState.getSelection();
    const currentKey = currentSelection.getStartKey();
    const currentBlock = editorState.getCurrentContent().getBlockForKey(currentKey);

    let newEditorState;

    if (currentBlock.getType() === "unstyled" && currentBlock.getText() === "") {
        // Current line is empty, we should convert to a gif atomic block
        // <INSERT MAGIC HERE>
    } else {
        // There's stuff here, lets create a new block
        newEditorState = AtomicBlockUtils.insertAtomicBlock(editorState, entityKey, " ");
    }

    return EditorState.forceSelection(
        newEditorState,
        newEditorState.getCurrentContent().getSelectionAfter()
    );
};

我不确定如何处理将当前块转换为原子块的情况。这是 Draft.js 的最佳实践吗?或者,我最好总是插入一个新块然后删除空块?

为清楚起见,Image Plugin 中也存在同样的问题,这不是我介绍的内容。

4

1 回答 1

0

你可以使用 https://draftjs.org/docs/api-reference-modifier/#setblocktype

const content = Modifier.setBlockType(content, editorState.getSelection(), 'atomic');
const newState = EditorState.push(editorState, content, 'change-block-type');
于 2020-07-06T20:31:15.673 回答