DraftJs-使用Modifier.removeInlineStyle()

时间:2018-11-20 20:29:46

标签: reactjs draftjs

我有一个用于设置字体大小的内联样式的功能。它可以正常工作,除非在循环使用几种字体大小后,我必须两次切换按钮。因此,为解决此问题,我想循环浏览当前部分的内容状态,删除所有当前字体大小样式,然后切换新样式。到目前为止,这是我所拥有的,除了似乎没有应用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>

1 个答案:

答案 0 :(得分:0)

我需要使用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'));
}