wangeditor富文本编辑器使用方法

583 阅读1分钟

components下的Editor组件(二次封装)

import E from 'wangeditor'

/**
* 这里用函数式组件
*/

let editor = null
function Editor(props) {

 const { value, onChange } = props;

 useEffect(() => {
   // 注:class写法需要在componentDidMount 创建编辑器
   editor = new E("#div1")

   editor.config.onchange = (newHtml) => {
       onChange(newHtml);
   }


   
  // 上传图片到服务器
 editor.config.uploadFileName = 'myFile'; //设置文件上传的参数名称
 editor.config.uploadImgServer = 'upload'; //设置上传文件的服务器路径
 editor.config.uploadImgMaxSize = 10 * 1024 * 1024; // 将图片大小限制为 3M
 editor.config.uploadImgMaxLength = 5;
 editor.config.uploadImgHooks = {
   
    success: function (xhr, editor, result) {
        console.log(xhr);
        // 图片上传并返回结果,图片插入成功之后触发
        // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果
    },
    fail: function (xhr, editor, result) {
        // 图片上传并返回结果,但图片插入错误时触发
        // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果
    },
    error: function (xhr, editor) {
        // 图片上传出错时触发
        // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象
    }
    
 }

   // 需要展示的菜单
   editor.config.menus = [
       'head',
       'bold',
       'image',
       'fontSize',
       'fontName',
       'italic',
       'underline',
       'strikeThrough',
       'indent',
       'lineHeight',
       'foreColor',
       'backColor',
       'link',
       'list',
       'todo',
       'justify',
       'quote',
       'table',
       'splitLine',
       'undo',
       'redo',
  ]

   /**一定要创建 */
   editor.create()



   return () => {
     // 组件销毁时销毁编辑器 注:class写法需要在componentWillUnmount中调用
     editor.destroy()
  }

 // 这里一定要加上下面的这个注释  
 // eslint-disable-next-line react-hooks/exhaustive-deps
}, [])

 useEffect(() => {
     if (editor) {
       editor.txt.html(value);
    }
}, [value])

 return (
   <div>
     <div id="div1"></div>
   </div>
);
}

export default Editor;

页面使用:(搭配antd的Form.Item)

import Editor from '../../../../../components/Editor';

.................................代码省略

<Form.Item
name="questionTitle"
label="试题题干"
rules={[
{
required: true,
message: '请输入试题题干',
},
]}
>
  <Editor />
</Form.Item>