首页 > 解决方案 > DraftJs - 使用 Modifier.removeInlineStyle() 用新的内容状态更新编辑器状态

问题描述

我有一个设置字体大小内联样式的功能。它主要工作,除了循环几个字体大小后,我必须切换按钮两次。所以为了解决这个问题,我想循环当前选择的内容状态,删除所有当前字体大小样式,然后切换新样式。这是我到目前为止所拥有的,除了Modifier.removeInlineStyle()似乎没有被应用,我仍然留下了我原来的问题。

状态设置:

constructor(props: RichTextEditorComponentProps) {
    super(props);
    this.state = this.propsToState(props);
}

propsToState(props: RichTextEditorComponentProps) {
    return {
        editorState: props.content ? EditorState.createWithContent(
            ContentState.createFromBlockArray(
                convertFromHTML(props.content).contentBlocks,
                convertFromHTML(props.content).entityMap
            )
        ) : EditorState.createEmpty()
    };
}

类中的方法:

onFontSizeStyleClick(fontStyle: string) {
    const contentState = this.state.editorState.getCurrentContent();
    const styles = this.state.editorState.getCurrentInlineStyle();
    const selection = this.state.editorState.getSelection();
    Object.keys(FontStyleMap).forEach(style => {
        if (styles.has(style)) {
            Modifier.removeInlineStyle(contentState, selection, style);
        }
    });
    this.onChange(RichUtils.toggleInlineStyle(this.state.editorState, fontStyle));
}

然后从以下位置调用:

<button
    type="button"
    className="style-button"
    onClick={() => this.onFontSizeStyleClick('fontSizeXS')}>
    SM
</button>
<button
    type="button"
    className="style-button"
    onClick={() => this.onFontSizeStyleClick('fontSizeNormal')}>
    N
</button>
<button
    type="button"
    className="style-button"
    onClick={() => this.onFontSizeStyleClick('fontSizeL')}>
    L
</button>
<button
    type="button"
    className="style-button"
    onClick={() => this.onFontSizeStyleClick('fontSizeXL')}>
    XL
</button>

标签: reactjsdraftjs

解决方案


我需要使用 EditorState.push 作为参数调用我的 onChange 方法:

onFontSizeStyleClick(fontStyle: string) {
    let contentState = this.state.editorState.getCurrentContent();
    const styles = this.state.editorState.getCurrentInlineStyle();
    const selection = this.state.editorState.getSelection();
    Object.keys(FontStyleMap).forEach(style => {
        if (styles.has(style)) {
            contentState = Modifier.removeInlineStyle(contentState, selection, style);
        }
    });
    contentState = Modifier.applyInlineStyle(contentState, selection, fontStyle);
    this.onChange(EditorState.push(this.state.editorState, contentState, 'change-inline-style'));
}

推荐阅读