React所见即所得草案将粗体,斜体或udenderlina应用于整个内容

时间:2019-09-03 15:10:59

标签: reactjs wysiwyg draftjs

我需要将粗体,斜体,下划线样式应用于编辑器的整个内容,而没有诸如对齐样式之类的选定文本,但我找不到解决办法。可以更改操作或处理程序吗?

1 个答案:

答案 0 :(得分:2)

是的,有可能。您可以在应用样式时更新SelectionState。 在这里,我们选择所有文本

const selection = editorState.getSelection().merge({
  anchorKey: currentContent.getFirstBlock().getKey(),
  anchorOffset: 0,
  focusOffset: currentContent.getLastBlock().getText().length,
  focusKey: currentContent.getLastBlock().getKey()
});

然后,我们应用新的selection

const editorStateWithAllSelection = EditorState.acceptSelection(
  editorState,
  selection
);

const newState = RichUtils.toggleInlineStyle(
  editorStateWithAllSelection,
  inlineStyle
)

如果您希望避免在最终结果中选择您的文本,我们可以应用我们的旧选择

const selectionBefore = editorState.getSelection();

// updating selection, toggling style ...

const editorStateWithSelectionBefore = EditorState.acceptSelection(
  newState,
  selectionBefore
);

setEditorState(editorStateWithSelectionBefore);

Codeandbox上的示例