我有以下功能
buttonToSelection(){
const editorState = this.state.editorState;
var selectionState = editorState.getSelection();
const newSelection = selectionState.merge({
anchorOffset: 1,
focusOffset: 10
})
const newEditorState = EditorState.forceSelection(editorState, newSelection);
this.editorChangeState(RichUtils.toggleInlineStyle(newEditorState,'STRIKEOUT'));
}
我想要实现的是点击按钮样式,使用STRIKEOUT将文本范围设置在1到10之间。该功能目前执行此操作,但也保留文本的选择。我只是想让它改变文本的样式。
答案 0 :(得分:1)
你做得差不多。但是,由于您已经为Draft提供了一个新的选择(适用于使用RichUtils添加样式),它将尝试渲染该选择。因此,在调用editorChangeState
之前,您必须再次将选择重置为其先前的值。以下是它的外观(带有一些过于描述性的变量):
buttonToSelection = () => {
const editorState = this.state.editorState;
const selectionState = editorState.getSelection();
const newSelection = selectionState.merge({
anchorOffset: 1,
focusOffset: 10
})
const editorStateWithNewSelection = EditorState.forceSelection(editorState, newSelection);
const editorStateWithStyles = RichUtils.toggleInlineStyle(editorStateWithNewSelection,'STRIKEOUT')
const editorStateWithStylesAndPreviousSelection = EditorState.forceSelection(
editorStateWithStyles,
selectionState
)
this.editorChangeState(editorStateWithStylesAndPreviousSelection);
}
Here's a fiddle展示了它的实际效果。确保在单击按钮之前在编辑器中至少编写了11个字符,否则它将会中断。