You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Draft.js富文本框如何编程插入文本并保留当前行内样式?

解决方案

你原有写法的问题在于currentSelection是插入文本前的光标/选区范围,插入文本后原选区已经被替换为新字符,直接用原有选区自然无法匹配到新插入的内容。

最优实现方案:插入时直接指定样式

Draft.js的Modifier.replaceText方法本身支持第四个参数传入行内样式集合,插入文本时会自动给新插入的内容应用这些样式,不需要额外调用applyInlineStyle,是性能最高也最简洁的实现:

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

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

    // 构造要应用的行内样式集合
    const inlineStyles = new Set();
    if (this.isSubscriptOn()) {
        inlineStyles.add('SUBSCRIPT');
    }
    // 其他需要默认应用的行内样式也可在此处添加

    let newContent = Modifier.replaceText(
        currentContent,
        currentSelection,
        characterToInsert,
        inlineStyles // 第四个参数传入样式集合
    );

    return EditorState.push(editorState, newContent, 'insert-characters');
}

特殊场景:插入后再修改样式的实现

如果你的业务逻辑需要先插入文本再做样式处理,可以手动构造新插入字符的选区范围:

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

    const currentContent = editorState.getCurrentContent(),
        currentSelection = editorState.getSelection();
    const startOffset = currentSelection.getStartOffset();
    const currentBlockKey = currentSelection.getStartKey();

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

    if (this.isSubscriptOn()) {
        // 手动构造新插入字符的选区
        const newCharSelection = new SelectionState({
            anchorKey: currentBlockKey,
            anchorOffset: startOffset,
            focusKey: currentBlockKey,
            focusOffset: startOffset + characterToInsert.length,
            isBackward: false
        });
        newContent = Modifier.applyInlineStyle(newContent, newCharSelection, 'SUBSCRIPT');
    }

    return EditorState.push(editorState, newContent, 'insert-characters');
}

内容的提问来源于stack exchange,提问作者tomashauser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 18:06:04