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

如何用指定文本重新填充DraftJS编辑器并替换现有内容?

解决DraftJS编辑器内容完全替换问题

不用依赖draftjs-utils的clearEditorContent方法(大概率是导入错误或版本兼容问题导致undefined),直接用DraftJS原生API就能实现内容完全替换,给你两种可行方案:

方案一:全选现有内容后替换

这种方式先选中编辑器内所有内容,再用新文本替换选中部分:

// 替换编辑器全部内容的函数
const replaceEditorContent = (editorState, text) => {
  const currentContent = editorState.getCurrentContent();
  // 创建覆盖整个内容的选区
  const fullSelection = new SelectionState({
    anchorKey: currentContent.getFirstBlock().getKey(),
    anchorOffset: 0,
    focusKey: currentContent.getLastBlock().getKey(),
    focusOffset: currentContent.getLastBlock().getLength(),
    isBackward: false,
  });

  // 替换全选内容为新文本
  const newContent = Modifier.replaceText(
    currentContent,
    fullSelection,
    text
  );

  const newEditorState = EditorState.push(
    editorState,
    newContent,
    'replace-fragment'
  );

  return EditorState.forceSelection(
    newEditorState,
    newContent.getSelectionAfter()
  );
};

// 修改原有的sendTextToEditor函数
const sendTextToEditor = (editorState, text) => {
  setEditorState(replaceEditorContent(editorState, text));
};

方案二:直接创建新内容状态替换

这种方式更简洁,直接用新文本生成全新的ContentState替换原有内容:

// 替换编辑器全部内容的函数
const replaceEditorContent = (editorState, text) => {
  // 用新文本创建ContentState
  const newContentState = ContentState.createFromText(text);
  // 生成新的EditorState并返回
  return EditorState.push(
    editorState,
    newContentState,
    'replace-fragment'
  );
};

// 修改原有的sendTextToEditor函数
const sendTextToEditor = (editorState, text) => {
  setEditorState(replaceEditorContent(editorState, text));
};

注意:确保已正确导入DraftJS相关API:

import { EditorState, ContentState, SelectionState, Modifier } from 'draft-js';

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 22:10:36