Draftjs 以编程方式将内联样式应用于文本
Draftjs apply inline styling to text programatically
我有以下功能
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'));
}
我想要实现的是在单击按钮样式时使用删除线将文本范围设置为 1 到 10 之间。该功能目前执行此操作,但也会保留文本的选择。我只是想让它改变文本的样式。
你几乎做对了。但是由于您已经为 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 个字符,否则它会中断。
我有以下功能
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'));
}
我想要实现的是在单击按钮样式时使用删除线将文本范围设置为 1 到 10 之间。该功能目前执行此操作,但也会保留文本的选择。我只是想让它改变文本的样式。
你几乎做对了。但是由于您已经为 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 个字符,否则它会中断。