DraftJS编辑器按退格键删除内容时如何获取被删除的粘贴图片信息
解决思路
你的图片是通过原子块存储的不可变实体,只需要在退格指令触发、Draft执行默认删除操作前,先根据当前编辑器的选中状态、光标位置判断即将被删除的内容是否包含你定义的图片实体,拿到实体中存储的图片id后调用服务端删除接口,再交给Draft执行默认删除逻辑即可。
具体实现
修改handleKeyCommand方法如下:
const handleKeyCommand = (command: string, editorState: EditorState): DraftHandleValue => { if (command === 'backspace') { const selection = editorState.getSelection(); const currentContent = editorState.getCurrentContent(); // 场景1:选中了多段内容按退格 if (!selection.isCollapsed()) { const blockMap = currentContent.getBlockMap(); const startKey = selection.getStartKey(); const endKey = selection.getEndKey(); // 遍历选中范围内的所有块 blockMap .skipUntil((_, key) => key === startKey) .takeUntil((_, key) => key === endKey) .concat(blockMap.get(endKey)) .forEach(block => { // 匹配图片原子块 if (block.getType() === 'atomic') { const entityKey = block.getEntityAt(0); if (!entityKey) return; const entity = currentContent.getEntity(entityKey); if (entity.getType() === PastedImageEntityType) { const { id } = entity.getData(); // 调用你的服务端删除接口 deleteImageFromServer(id); } } }); return 'not-handled'; } // 场景2:光标无选中,按退格删除前一个内容 const offset = selection.getAnchorOffset(); const currentBlockKey = selection.getAnchorKey(); const currentBlock = currentContent.getBlockForKey(currentBlockKey); // 光标在当前块最开头,按退格会删除前一个块 if (offset === 0) { const prevBlockKey = currentContent.getKeyBefore(currentBlockKey); if (!prevBlockKey) return 'not-handled'; const prevBlock = currentContent.getBlockForKey(prevBlockKey); if (prevBlock.getType() === 'atomic') { const entityKey = prevBlock.getEntityAt(0); if (!entityKey) return 'not-handled'; const entity = currentContent.getEntity(entityKey); if (entity.getType() === PastedImageEntityType) { const { id } = entity.getData(); deleteImageFromServer(id); } } } return 'not-handled'; } return 'not-handled'; }
补充说明
- 如果需要覆盖删除键(delete)、剪切操作删除图片的场景,同理可以监听
delete指令、handleBeforeInput等钩子复用上面的判断逻辑。 - 为了避免用户删除后撤销恢复、再次删除触发重复删除请求,可以给后端删除接口加幂等,或者前端维护已删除图片id的缓存池做判断。
内容的提问来源于stack exchange,提问作者Zhongwei Xu
相关产品推荐
相关产品推荐

