首页 > 解决方案 > 如何在草稿 js 中更新文本并同时切换新的内联样式?

问题描述

当我单击特定按钮时,handleMouseDown函数会触发onMouseDown事件:

handleMouseDown(e) {
    e.preventDefault();
    this.props.handleMouseDown(this.props.symbol);
}

它触发了handleMouseDown实际编辑器类的函数,如下所示:

handleMouseDown(symbol) {
    let newState = this.insertText(symbol);
        
    this.setState({ editorState: newState }); // First action
    this.toggleInlineStyle("SUBSCRIPT"); // Second action
}

问题是我一次只能执行一项操作 - 如果我注释掉文本插入,则切换下标内联样式,如果我注释掉切换插入新文本的内联样式,但是如果我离开它喜欢这样,当内联样式更改时,符号不会被插入,最后,如果我更改顺序,符号会被插入,但内联样式不会改变。如何同时正确执行这两项操作?

插入文本函数:

insertText(characterToInsert) {
    let editorState = this.state.editorState;

    const currentContent = editorState.getCurrentContent(),
        currentSelection = editorState.getSelection();

    let newContent = Modifier.replaceText(
        currentContent,
        currentSelection,
        characterToInsert
    );

    let newEditorState = EditorState.push(editorState, newContent, 'insert-characters');

    return newEditorState;
}

标签: reactjsdraftjs

解决方案


您可以使用以下命令直接将内联样式添加到新的编辑器状态:EditorState.setInlineStyleOverride

所以它看起来像这样:

handleMouseDown(symbol) {
    let newState = this.insertText(symbol);
    EditorState.setInlineStyleOverride(newState, OrderedSet.of('SUBSCRIPT'));
        
    this.setState({ editorState: newState });
}

推荐阅读