将空块添加到Draft.js而不移动选择

tob*_*sen 6 reactjs draftjs

在不改变SelectionState的情况下,将一个空的无格式块添加到Draft.js编辑器的最佳方法是什么?

tob*_*sen 13

这就是我最终做的事情:

import { List } from 'immutable'
import {
  EditorState,
  ContentState,
  ContentBlock,
  genKey
} from 'draft-js'

const addEmptyBlock = (editorState) => {
  const newBlock = new ContentBlock({
    key: genKey(),
    type: 'unstyled',
    text: '',
    characterList: List()
  })

  const contentState = editorState.getCurrentContent()
  const newBlockMap = contentState.getBlockMap().set(newBlock.key, newBlock)

  return EditorState.push(
    editorState,
    ContentState
      .createFromBlockArray(newBlockMap.toArray())
      .set('selectionBefore', contentState.getSelectionBefore())
      .set('selectionAfter', contentState.getSelectionAfter())
  )
}
Run Code Online (Sandbox Code Playgroud)

  • 当我使用它时,块被附加到末尾。 (2认同)