第一步是使用applyInlineStyle: function (contentState: ContentState, selectionState: SelectionState, inlineStyle: string)
静态Modifier
类的功能。如您所见 - 它需要选择我们希望应用样式的区域。我们将使用以下set
方法创建这样的样式immutable.js
:
const textToInsertSelection = currentSelection.set('focusOffset', currentSelection.getFocusOffset() + textToInsert.length);
然后我们将获得OrderedSet
当前的内联样式并将它们中的每一个应用于上述选择:
let inlineStyles = editorState.getCurrentInlineStyle();
inlineStyles.forEach(inLineStyle => newContent = Modifier.applyInlineStyle(newContent, textToInsertSelection, inLineStyle));
如果我们停在这里,文本将在被选中时放入输入字段(蓝色矩形会出现在它周围)。为了避免这种行为,让我们强制选择插入文本的末尾:
newState = EditorState.forceSelection(newState, textToInsertSelection.set('anchorOffset', textToInsertSelection.getAnchorOffset() + textToInsert.length));
整个函数如下所示:
insertText(textToInsert) {
let editorState = this.state.editorState;
const currentContent = editorState.getCurrentContent();
const currentSelection = editorState.getSelection();
let newContent = Modifier.replaceText(
currentContent,
currentSelection,
textToInsert
);
const textToInsertSelection = currentSelection.set('focusOffset', currentSelection.getFocusOffset() + textToInsert.length);
let inlineStyles = editorState.getCurrentInlineStyle();
inlineStyles.forEach(inLineStyle => newContent = Modifier.applyInlineStyle(newContent, textToInsertSelection, inLineStyle));
let newState = EditorState.push(editorState, newContent, 'insert-characters');
newState = EditorState.forceSelection(newState, textToInsertSelection.set('anchorOffset', textToInsertSelection.getAnchorOffset() + textToInsert.length));
return newState;
}