代码之家  ›  专栏  ›  技术社区  ›  Sandra Willford

DraftJs-使用Modifier.removeInlineStyle()用新的内容状态更新编辑器状态

  •  0
  • Sandra Willford  · 技术社区  · 6 年前

    我有一个设置字体大小内联样式的函数。它主要工作,除了在几个字体大小循环之后,我必须切换按钮两次。为了解决这个问题,我想循环查看当前选择的内容状态,删除所有当前字体大小样式,然后切换新样式。这就是我目前所拥有的,除了 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 回复  |  直到 6 年前
        1
  •  0
  •   Sandra Willford    6 年前

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