react如何使用ueditor
使用 UEditor 在 React 项目中
在 React 项目中集成 UEditor(百度富文本编辑器)需要解决几个关键问题:UEditor 是基于传统 DOM 操作的库,而 React 是声明式框架,需要通过手动挂载 DOM 并管理生命周期。
安装 UEditor
下载 UEditor 官方资源包(通常为 ZIP 文件),解压后放置到项目的 public 目录下。例如:

public/
└── ueditor/
├── dialogs/
├── lang/
├── themes/
└── ueditor.all.js
创建 React 组件封装
新建一个 React 组件(如 UEditor.jsx),动态加载 UEditor 资源并初始化:
import React, { useEffect, useRef } from 'react';
const UEditor = ({ config, onChange }) => {
const editorRef = useRef(null);
const scriptRef = useRef(null);
useEffect(() => {
// 动态加载 UEditor 主脚本
scriptRef.current = document.createElement('script');
scriptRef.current.src = '/ueditor/ueditor.all.js';
scriptRef.current.onload = () => {
window.UEDITOR_CONFIG = config || {
serverUrl: '', // 后端接口地址(如需要上传功能)
initialFrameHeight: 300,
};
editorRef.current = window.UE.getEditor('editorContainer');
editorRef.current.addListener('contentChange', () => {
onChange?.(editorRef.current.getContent());
});
};
document.body.appendChild(scriptRef.current);
return () => {
// 清理资源
if (editorRef.current) {
editorRef.current.destroy();
}
if (scriptRef.current) {
document.body.removeChild(scriptRef.current);
}
};
}, []);
return <div id="editorContainer" />;
};
export default UEditor;
使用组件
在父组件中调用封装好的 UEditor:

import React, { useState } from 'react';
import UEditor from './UEditor';
const App = () => {
const [content, setContent] = useState('');
return (
<div>
<UEditor
onChange={setContent}
config={{ serverUrl: '/api/upload' }}
/>
<div>实时内容:{content}</div>
</div>
);
};
配置后端接口(可选)
如果需要图片上传功能,需配置 serverUrl 指向后端接口。例如 Node.js 的 Express 服务:
const express = require('express');
const multer = require('multer');
const app = express();
const upload = multer({ dest: 'uploads/' });
app.post('/api/upload', upload.single('upfile'), (req, res) => {
res.json({
state: 'SUCCESS',
url: `/uploads/${req.file.filename}`,
title: req.file.originalname,
});
});
样式调整
在 index.html 中引入 UEditor 的 CSS:
<link rel="stylesheet" href="/ueditor/themes/default/css/ueditor.css" />
注意事项
- 多实例问题:避免在同一页面多次初始化 UEditor,可能导致冲突。
- SSR 兼容:服务端渲染时需通过动态导入(
next/dynamic或条件渲染)避免报错。 - 版本差异:UEditor 不同版本配置参数可能不同,需查阅对应版本文档。
通过这种方式,可以在 React 应用中实现完整的富文本编辑功能,同时保持 React 的数据流管理。






