我正在尝试用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,
});
};发布于 2017-07-07 04:48:12
我想通了。
const contentAfterSelectionRemoval = contentBeforeAtomicBlock.blockMap.delete(blockToRemoveKey);这看起来像是一个不可变状态中的反模式,所以我最终从另一个角度来处理这个问题,实际上并没有使用这个有效的解决方案。
发布于 2017-06-29 12:18:59
如果任何其他参数都可以,将focusOffset设置为1应该是可行的。
https://stackoverflow.com/questions/44781976
复制相似问题