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

React Draft Wysiwyg中convertFromHTML回显HTML内容报错求助

React Draft Wysiwyg HTML回显编辑器错误排查与解决

场景与问题

我用React Draft Wysiwyg搭建了富文本编辑器,已经通过下面的代码成功将编辑器内容转为HTML并存入数据库:

const [editorState, setEditorState] = useState(() =>
    EditorState.createWithContent(ContentState.createFromText(''))
)

draftToHtml(convertToRaw(editorState.getCurrentContent()))  // 生成HTML格式内容

现在想把数据库里的HTML内容回显到编辑器中编辑,用以下代码时触发了类型错误:

const contentfromhtml = convertFromHTML(selectedhtmltext);
setEditorState(
    EditorState.createWithContent(ContentState.createFromText(contentfromhtml))
)

错误提示:

Argument of type '{ contentBlocks: ContentBlock[]; entityMap: any; }' is not assignable to parameter of type 'string'.ts(2345)
const contentfromhtml: {
    contentBlocks: Draft.Model.ImmutableData.ContentBlock[];
    entityMap: any;
}

错误根源

convertFromHTML()的返回值是一个包含contentBlocks和entityMap的对象,但ContentState.createFromText()只能接收字符串类型的参数,两者类型不匹配,所以抛出了类型错误。

修复代码

直接用ContentState.createFromBlockArray()方法,结合convertFromHTML()返回的内容块和实体映射来创建ContentState,再传入编辑器状态:

const { contentBlocks, entityMap } = convertFromHTML(selectedhtmltext);
const contentState = ContentState.createFromBlockArray(contentBlocks, entityMap);
setEditorState(EditorState.createWithContent(contentState));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 20:22:19