【问题标题】:Draft.js - convert current block to Atomic BlockDraft.js - 将当前块转换为原子块
【发布时间】:2020-05-07 14:14:04
【问题描述】:

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

要插入 GIF,我将遵循图像插件中的示例 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 的最佳实践吗?或者,我最好总是插入一个新块,然后删除空块?

为了清楚起见,同样的问题也存在于图像插件中,这不是我介绍的。

【问题讨论】:

    标签: javascript reactjs draftjs draft-js-plugins


    【解决方案1】:

    你可以使用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');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-28
      • 1970-01-01
      • 2018-07-06
      • 1970-01-01
      • 2015-07-31
      • 2020-03-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多