wangEditor 富文本编辑器使用
框架: react hooks
链接: 官方文档参考
富文本编辑器组件
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import { useState, useEffect } from 'react';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import type { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import { upload } from '@/services/myEditor';
import { message } from 'antd';/*** 富文本编辑器* @param props* @constructor*/
function MyEditor(props: any) {const { data, onChange } = props;/*** editor 实例*/const [editor, setEditor] = useState<IDomEditor | null>(null);/*** 编辑器内容*/const [html, setHtml] = useState('');/*** 初始化*/useEffect(() => {setHtml(data);}, []);/*** 工具栏配置*/const toolbarConfig: Partial<IToolbarConfig> = {};/*** 上传文件* @param file* @param insertFn*/const update = (file: any, insertFn: any) => {const imgData = new FormData();imgData.append('file', file);//调接口,上传图片upload(imgData).then((res) => {if (res.code == 0) {//接口调用成功,将上传文件插入到富文本中去insertFn(res.data.url, res.data.name);} else {message.error('上传失败');}});};/*** 编辑器配置*/const editorConfig: Partial<IEditorConfig> = {placeholder: '请输入内容...',// 菜单操作设置MENU_CONF: {uploadImage: {// 上传图片配置customUpload: update,server: '/web/v1/files', // 这里是接口},uploadVideo: {// 上传视频配置customUpload: update,server: '/web/v1/files', // 这里是接口},},};/*** 及时销毁 editor ,重要!*/useEffect(() => {return () => {if (editor == null) return;editor.destroy();setEditor(null);};}, [editor]);const handleChange = (el: any) => {if (onChange) onChange(el.getHtml());};return (<><div style={{ border: '1px solid #ccc', zIndex: 100 }}><Toolbareditor={editor}defaultConfig={toolbarConfig}mode="default"style={{ borderBottom: '1px solid #ccc' }}/><EditordefaultConfig={editorConfig}value={html}onCreated={setEditor}onChange={handleChange}mode="default"style={{ height: '300px', overflowY: 'hidden' }}/></div></>);
}export default MyEditor;
使用
<Form.Item{...formItemLayout}name="content"label="富文本内容"rules={[{ required: false, message: '请输入富文本内容' }]}initialValue={params?.content ? params?.content : ''}
><MyEditor data={params?.content ? params?.content : ''} />
</Form.Item>