一次更新editorState,包含两个操作

时间:2017-04-13 16:57:10

标签: draftjs draft-js-plugins

当我进入space栏时,我试图将一个单词分成两个单词。我的文本中的每个单词都是一个实体,所以当我将一个单词拆分为两个时,我需要更新文本并创建一个新实体。

我正在使用Modifier模块进行这两项更新。

const editorStateAfterText = 
  EditorState.push(
    editorState,
    Modifier.insertText(
      contentState,
      selectionState,
      ' ',
    ),
    command,
  );
const editorStateAfterEntity =
  EditorState.push(
    editorStateAfterText,
    Modifier.applyEntity(
      contentState,
      newSelectionState,
      newEntityKey
    ),
    command,
  );
this.setState({editorState: editorStateAfterEntity})

我正在尝试一次更新两个操作的编辑器状态。如果另一个不存在,它们都可以工作。当两者存在时,它只更新最后一个。

有没有办法更新文本(拆分单词)并将新实体添加到entityMap

1 个答案:

答案 0 :(得分:1)

正如文档https://draftjs.org/docs/api-reference-editor-state.html#push中所定义的,push要求3个参数:editorStatecontentStatecommand

我在editorStateAfterEntity通过editorState传递更新的editorStateAfterText参数时做得很好,但我忽略了更新的contentState

所以这是最终的工作方式:

  const contentAfterText = Modifier.insertText(
    contentState,
    selectionState,
    ' ',
  );
  const editorStateAfterText = EditorState.push(
    editorState,
    contentAfterText,
    command,
  );
  const contentStateAfterTextAndEntity = Modifier.applyEntity(
    contentAfterText,
    newSelectionState,
    newEntityKey
  );
  const editorStateAfterTextAndEntity = EditorState.push(
    editorStateAfterText,
    contentStateAfterTextAndEntity,
    command,
  );
  this.setState({editorState: editorStateAfterTextAndEntity});