react如何安装ueditor
安装 UEditor 到 React 项目
在 React 项目中集成 UEditor(百度富文本编辑器)需要手动处理 UEditor 的依赖和配置,以下是具体步骤:
下载 UEditor 源码
从 UEditor 官方 GitHub 仓库或百度官网下载最新版本的 UEditor 源码。解压后,将整个文件夹(通常命名为 ueditor)放入 React 项目的 public 目录下,确保可以通过公共路径访问。
引入 UEditor 脚本
在 public/index.html 中直接引入 UEditor 的配置文件与核心脚本:
<script type="text/javascript" src="%PUBLIC_URL%/ueditor/ueditor.config.js"></script>
<script type="text/javascript" src="%PUBLIC_URL%/ueditor/ueditor.all.min.js"></script>
创建 React 组件封装 UEditor
新建一个 React 组件(如 UEditor.js),通过 useEffect 初始化 UEditor 实例:
import React, { useEffect, useRef } from 'react';
const UEditor = ({ id, config, onChange }) => {
const editorRef = useRef(null);
useEffect(() => {
// 确保全局 UE 对象存在
if (typeof window.UE !== 'undefined') {
editorRef.current = window.UE.getEditor(id, config);
// 监听内容变化
editorRef.current.addListener('contentChange', () => {
onChange?.(editorRef.current.getContent());
});
}
return () => {
// 组件卸载时销毁编辑器
if (editorRef.current) editorRef.current.destroy();
};
}, [id, config]);
return <script id={id} type="text/plain"></script>;
};
export default UEditor;
配置 UEditor 路径
在 ueditor.config.js 中修改服务器端请求的 URL 配置,确保与项目后端接口匹配:
window.UEDITOR_HOME_URL = '/ueditor/'; // 根据 public 路径调整
window.UEDITOR_SERVER_URL = 'http://your-backend-api/controller.php'; // 后端上传接口
使用组件
在父组件中调用 UEditor 并传入必要的参数:
import UEditor from './UEditor';
const App = () => {
const handleContentChange = (content) => {
console.log('编辑器内容:', content);
};
return (
<UEditor
id="editor"
config={{
initialFrameWidth: '100%',
initialFrameHeight: 500,
}}
onChange={handleContentChange}
/>
);
};
处理跨域上传(可选)
如果后端接口存在跨域问题,需在后端配置 CORS 或通过代理转发请求。例如,在 vite.config.js 中配置代理:
server: {
proxy: {
'/ueditor/controller.php': {
target: 'http://your-backend-api',
changeOrigin: true,
},
},
}
注意事项
- UEditor 依赖全局
window.UE对象,需确保脚本加载顺序正确。 - 生产环境下需检查静态资源路径是否正确部署。
- 若使用 TypeScript,需声明全局
UE类型:declare global { interface Window { UE: any; } }







