富文本编辑器 WangEditor
这是一个自定义的 React 组件 WangEditorFrame,它通过 iframe
内嵌的方式实现了 @wangeditor/editor-for-react
的隔离渲染,适用于需要避免编辑器污染主文档 CSS、JS 的场景。
📦 引入方式
import { WangEditor } from '@npmqg/react-ui-editor';
🧩 使用示例
- 示例
- 源码
<WangEditor
ref={null}
value="<p>初始内容</p>"
width="100%"
height="600px"
readOnly={false}
bordered
className="my-editor"
toolbarConfig={{
toolbarKeys: ['bold', 'italic', 'underline'],
}}
editorConfig={{
placeholder: '请输入内 容...',
}}
onChange={(html) => {
console.log('编辑内容变更:', html);
}}
onCreated={(editorInstance) => {
console.log('编辑器初始化完成', editorInstance);
}}
onSave={() => {
console.log('触发保存(Ctrl + S)');
}}
/>
🧩 Props
Prop | 类型 | 默认值 | 描述 |
---|---|---|---|
value | string | '' | 初始内容(HTML 格式) |
width | string | '100%' | 编辑器宽度 |
height | string | '500px' | 编辑器高度 |
readOnly | boolean | false | 是否为只读模式 |
bordered | boolean | true | 是否显示边框(尚未使 用) |
className | string | '' | 外层 div 的样式类名 |
toolbarConfig | Partial<IToolbarConfig> | {} | 工具栏配置 |
editorConfig | Partial<IEditorConfig> | { placeholder: '请输入内容...' } | 编辑器配置 |
onChange | (html: string) => void | () => null | 内容发生变化时的回调 |
onCreated | (editor: IDomEditor) => void | () => null | 编辑器初始化完成的回调 |
onSave | () => void | () => null | 用户按下 Ctrl+S 时触发的保存事件 |
🧠 技术实现要点
- 使用
iframe
隔离 DOM 环境,防止编辑器影响主站样式; - 利用
Blob + URL.createObjectURL
注入React、ReactDOM、wangEditor
的 JS 资源; - 将编辑器组件渲染到 iframe 中的
div#wangEditorWrap
; - 支持读取 CSS 变量(主题色)并通过
postMessage
传给iframe
实现动态主题切换; - 使用
useUpdateEffect
实现value
内容与外部同步; - 使用
useImperativeHandle
为未来扩展预留方法(如暴露getEditor()
);
🧩 注意事项
-
只读模式和编辑模式不能共存,由
readOnly
控制:readOnly = true
会直接渲染 HTML;readOnly = false
会使用 wangEditor 实例进行初始化和内容监听。
-
跨文档通信需通过
window.postMessage
处理,主题切换与保存操作依赖于消息事件。 -
资源管理建议使用 CDN 或独立文件引入,当前代码通过字符串形式引入多个 JS/CSS 字符串,需谨慎处理大小和缓存。
💬 主题自定义支持(CSS 变量)
:root {
--primary-section-color: #f0f2f5;
--font-3-color: #333333;
--border-color: #d9d9d9;
}