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

如何为Material UI的react-mui-draft-wysiwyg HTML编辑器设置初始状态

实现react-mui-draft-wysiwyg设置初始HTML内容的方案

该编辑器基于Draft.js实现,核心逻辑是先把你现有的HTML字符串转换为Draft可识别的EditorState对象,再绑定为编辑器的初始状态即可。

具体实现步骤

  • 第一步:导入所需依赖,包括编辑器组件、状态转换工具和Draft.js核心方法
  • 第二步:将你的初始HTML字符串转换为EditorState作为状态初始值
  • 第三步:把状态绑定到编辑器组件的对应属性上

完整示例代码

import React, { useState } from 'react';
import MUIWysiwyg, { htmlToDraft } from 'react-mui-draft-wysiwyg';
import { EditorState } from 'draft-js';

export default function CustomEditor() {
  // 你要设置的初始HTML片段
  const initialHtml = '<h1>header</h1>';
  // 转换HTML为Draft可用的EditorState作为初始值
  const [editorState, setEditorState] = useState(() => {
    const contentState = htmlToDraft(initialHtml);
    return EditorState.createWithContent(contentState);
  });

  return (
    <MUIWysiwyg
      editorState={editorState}
      onChange={newState => setEditorState(newState)}
    />
  );
}

如果你使用的初始HTML包含自定义标签、内联样式或特殊格式,可自行配置htmlToDraft的转换规则适配业务场景,h1~h6、p、列表这类基础HTML标签无需额外配置可直接识别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 23:12:01