如何在 Draft.js 中正确添加没有 2 个空行的图像(原子)

How to properly add image (atomic) without 2 empty lines in Draft.js

默认情况下 draft.js 放置任何具有 2 个空行的原子类型块(1 个在 atimic 之前,1 个在 atimic 之后)。此行为是 draft.js 和 here 中缺乏原子选择的结果。我怎样才能摆脱那些线?我还没有在 Modifier 中找到任何合适的功能。 也许有人有另一种解决方案来解决这个问题,因为现在看起来不太好

更新:我找到适合我的解决方案:

      const { editorState } = this.props;
      const contentState = editorState.getCurrentContent();
      const entityKey = Entity.create('image', 'IMMUTABLE', {src: this.state.url});
      const with_atomic = AtomicBlockUtils.insertAtomicBlock(editorState, entityKey, ' ');
      const new_content_state = with_atomic.getCurrentContent();
      const block_map = new_content_state.getBlockMap();
      const current_atomic_block = block_map.find(block => {
         if (block.getEntityAt(0) === entityKey) {
            return block
         }
      });
      const atomic_block_key = current_atomic_block.getKey();
      const block_before = new_content_state.getBlockBefore(atomic_block_key).getKey();
      const new_block_map = block_map.filter(block => {
         if ((block.getKey() !== block_before) ) {
            return block
         }
      });
      const newContentState = contentState.set('blockMap', new_block_map);
      const newEditorState = EditorState.createWithContent(newContentState);
      this.props.onChange(newEditorState);

如果您需要在插入时处理非折叠选择,那不是几行代码。如果你只需要删除原子周围的两行,也许这段代码有效:

const newAtomicBlock = contentState.getBlockMap().find(b=>b.getEntityAt(0)===entityKey).getKey();
const newBlockMap = contentState.getBlockMap().delete(contentState.getBlockBefore(newAtomicBlock)).delete(contentState.getBlockAfter(newAtomicBlock));
const newContentState = contentState.set('blockMap', newBlockMap);
const newEditorState = EditorState.push(editorState, newContentState, 'delete-empty-lines');