记录一下富文本编辑器的使用

1,749 阅读3分钟

常见的富文本编辑器有很多,比如uEditor、ckEditor、wangEditor、tinymce。 今天主要介绍wngEditor和tinymce两款编辑器的使用。

一、wangEditor

wangEditor本身轻便,使用起来比较简单,通过基本案列看下:

import E from 'wangeditor';
class Editor extends Component {
    state = {
        editorContent: null
    }

    componentDidMount() {
        const elem = this.refs.editorElem;
        const editor = new E(elem);
        editor.config.menus = [
            'head', // 标题
            'bold', // 粗体
            'fontSize', // 字号
            'fontName', // 字体
            'italic', // 斜体
            'underline', // 下划线
            'strikeThrough', // 删除线
            'foreColor', // 文字颜色
            'backColor', // 背景颜色
            'link', // 插入链接
            'list', // 列表
            'justify', // 对齐方式
            'emoticon', // 表情
            'table', // 表格
            'undo', // 撤销
            'redo' // 重复
        ];
        // 使用 onchange 函数监听内容的变化,并实时更新到 state 中
        editor.config.onchange = html => {
            this.setState({
                editorContent: html
            });
            this.props.onChange('text_report', this.state.editorContent);
        };
        editor.create();
    }

    render() {
        return (
            <div ref='editorElem' style={{ textAlign: 'left', height: '69vh' }} />
        );
    }
}

这就是一个初始化的过程。还又一个重要配置就是 editor.config.pasteFilterStyle = false,这是表明在粘贴复制时,是否开启样式过滤。经过验证,此配置项在mac系统中是正常的,但是在windows系统中,由wps/office中Excel粘贴到富文本是不起作用的,会丢失样式,但是word中是正常的,官方的解释是,wps中粘贴的样式不符合w3c的标准。 目前wangEditor的V5版本也在公测中,与前面的版本相比,在写法上还是变化很大。

二、Tinymce

tinymce号称是最强大的编辑器,的确如此,有很多可配置的插件,附中文文档地址,更详细的使用大家看文档。通过案例看下在react中的基本使用:

 import React, { useRef } from 'react';
 import { Editor } from '@tinymce/tinymce-react';

 export default function App() {
   const editorRef = useRef(null);
   const log = () => {
     if (editorRef.current) {
       console.log(editorRef.current.getContent());
     }
   };
   return (
     <>
       <Editor
         onInit={(evt, editor) => editorRef.current = editor}
         initialValue="<p>This is the initial content of the editor.</p>"
         init={{
           height: 500,
           menubar: false,
           plugins: [
             'advlist autolink lists link image charmap print preview anchor',
             'searchreplace visualblocks code fullscreen',
             'insertdatetime media table paste code help wordcount'
           ],
           toolbar: 'undo redo | formatselect | ' +
           'bold italic backcolor | alignleft aligncenter ' +
           'alignright alignjustify | bullist numlist outdent indent | ' +
           'removeformat | help',
           content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
           onEditorChange={onEditorChange}
           onChange={onChange}
         }}
       />
       <button onClick={log}>Log editor content</button>
     </>
   );
 }

content_style主要是用来修改编辑器内部的样式,可以强制修改,样式层级更高。onEditorChange事件在项目初始化的时候就会触发,onChange事件是在内容变化的时候会触发。 在项目初始化时有三种方式:

  1. 使用tiny Cloud初始化项目 <Editor apiKey='your-api-key' init={{ /* your other settings */ }} /> 这种初始化编辑器时,需要在官网注册账号,得倒appKey,并且在部署到线上时,需要在账号个人中心配置线上环境的域名,且在初始化编辑器时,会有很大的延迟,体验不是很好。

  2. 采用TinyMCE Self-hosted <Editor tinymceScriptSrc="/path/to/tinymce.min.js" />,这种方式是本地部署项目,将从官网下载的tinymce文件解压后放到项目的静态资源(/public)目录中即可。将下载的语言包放到tinymce文件的lang文件夹下,然后修改配置项语言为对应编码即可。解决了使用加载时间长,体验不好的情况。使用到的一些高级插件需要另外下载,默认下载目录中只包含一些基础插件,比如pastPower强力粘贴的插件,此插件可以将复制的内容原封不动的粘贴到编辑器中。解决了wangEditor粘贴时不保留wps样式的问题。

  3. 在html文件中采用script的方式 <script src="%PUBLIC_URL%/tinymce/tinymce.min.js"></script>,此方法只需将tinymce文件放到公司服务器中,在<header>标签中引入文件即可,配置项没什么变化。

pastPower插件的使用

此插件是高级插件,很强大。当使用到时,本地部署项目时,需要单独下载插件,然后将下载的js,放在tinymce文件的plugins文件夹下。在你粘贴文件时会有一个弹框,只需要修改powerpaste_word_import配置项为merge,可关闭弹框。采用的是tiny Cloud的方式初始化,此配置项需要用函数的方式去返回值,如下:

powerpaste_word_import: function() {
    // use a native confirm dialog to prompt the user to choose between clean and merge
    return new Promise(function (resolve) {
      if (confirm('Would you like to keep formatting?')) {
        resolve('merge');
      } else {
        resolve('clean');
      }
    });
  }

此编辑器更多使用细节,看看官网。