Draftjs试图删除一个原子块

时间:2017-06-27 13:46:40

标签: javascript reactjs draftjs

我正在尝试使用Modifier.removeRange从draftjs编辑器中删除原子块。据我所知,我传递了所有正确的参数,但是用于删除的SelectionState永远不会被删除。 这是我的代码。这也增加了一个新的原子块。该部分工作正常,它是删除方面返回我传入的相同contentState。

upload_block_selection_state是要删除的SelectionState对象。此对象在呈现时从editorState.getSelection()获取。看起来像这样。

upload_block_selection_state = {
 anchorKey: "c1kpk",
 anchorOffset: 0,
 focusKey: "c1kpk",
 focusOffset: 0,
 isBackward: false
}

以下是应该删除上传块然后添加新块的功能。添加作品,删除什么都不做。

function addAndRemoveMediaBlock(
    entityURL,
    entityType,
    editorState,
    setEditorState,
    upload_block_selection_state
){
    const contentBeforeAtomicBlock      = editorState.getCurrentContent();
    const contentAfterSelectionRemoval  = Modifier.removeRange(
        contentBeforeAtomicBlock,
        upload_block_selection_state,
        'forward'
    );


    const contentStateWithEntity        = contentAfterSelectionRemoval.createEntity(entityType, 'IMMUTABLE', { src: entityURL });
    const entityKey                     = contentStateWithEntity.getLastCreatedEntityKey();
    const editorStateAfterAtomicBlock   = AtomicBlockUtils.insertAtomicBlock(
        editorState,
        entityKey,
        entityKey
    );

    /* 
        below here relevant only to removing the empty block.  
        */    
    const selectionStateBeforeAtomicBlock = editorState.getSelection();
    const anchorKeyBeforeAtomicBlock      = selectionStateBeforeAtomicBlock.getAnchorKey();
    const contentAfterAtomicBlock         = editorStateAfterAtomicBlock.getCurrentContent();
    const blockSelectedBefore             = contentAfterAtomicBlock.getBlockForKey(anchorKeyBeforeAtomicBlock);

    const finalEditorState = (() => {
        if(blockSelectedBefore.getLength() === 0){
            const keyBefore                    = blockSelectedBefore.getKey();
            const newBlockMap                  = contentAfterAtomicBlock.blockMap.delete(keyBefore);
            const contentWithoutEmptyBlock     = contentAfterAtomicBlock.set('blockMap', newBlockMap);
            const editorStateWithoutEmptyBlock = EditorState.push(editorStateAfterAtomicBlock, contentWithoutEmptyBlock, 'remove-block');
            return EditorState.forceSelection(editorStateWithoutEmptyBlock, contentWithoutEmptyBlock.getSelectionAfter());
        }else{
            return editorStateAfterAtomicBlock;
        }
    })();
    setEditorState({
        editorState: finalEditorState,
    });
};

2 个答案:

答案 0 :(得分:1)

我明白了。

const contentAfterSelectionRemoval  = contentBeforeAtomicBlock.blockMap.delete(blockToRemoveKey);

这似乎是一个不可变状态下的反模式,所以我最终从另一个角度接近问题并且实际上没有使用这个工作解决方案。

答案 1 :(得分:0)

如果任何其他参数都合适,

focusOffset设置为1应该有效。