在react中使用富文本编辑器 react+wangEditor

    • 前言
    • 第一步
    • 第二步
    • 第三步
    • 第四步
    • 第五步
    • 完整代码
    • 写在最后

前言

近日在使用react写项目的过程中需要使用到富文本编辑器,之前使用的一直是百度富文本框,这次想换一个,于是看到了一个比较轻量级的富文本编辑器:wangeditor ,正好也满足我当前所需要的需求,所以就决定使用这款编辑器了。这篇文章给了我很大的帮助,感谢作者:react中引入富文本编辑器wangeditor,react打包项目直接运行文件,话不多说,进入正题

第一步

先npm导入wangEditor:

npm install wangeditor --save

第二步

引入wangeditor包:

import E from 'wangeditor'

第三步

创建render函数:

render() {
        return (
            <div className="shop">
                <div className="text-area" >
                    <div ref="editorElemMenu"
                         style={{backgroundColor:'#f1f1f1',border:"1px solid #ccc"}}
                         className="editorElem-menu">

                    </div>
                    <div
                        style={{
                            padding:"0 10px",
                            overflowY:"scroll",
                            height:300,
                            border:"1px solid #ccc",
                            borderTop:"none"
                        }}
                        ref="editorElemBody" className="editorElem-body">

                    </div>
                </div>
            </div>
        );
    }

第四步

    constructor(props) {
        super(props);
        this.state = {
            editorContent:''
         };
    }

第五步

在组件渲染完毕(componentDidMount)之后实例化编辑器:

componentDidMount() {
        const elemMenu = this.refs.editorElemMenu;
        const elemBody = this.refs.editorElemBody;
        const editor = new E(elemMenu,elemBody)
        // 使用 onchange 函数监听内容的变化,并实时更新到 state 中
        editor.customConfig.onchange = html => {
            console.log(editor.txt.html())
            this.setState({
                // editorContent: editor.txt.text()
                editorContent: editor.txt.html()
            })
        }
        editor.customConfig.menus = [
            'head',  // 标题
            'bold',  // 粗体
            'fontSize',  // 字号
            'fontName',  // 字体
            'italic',  // 斜体
            'underline',  // 下划线
            'strikeThrough',  // 删除线
            'foreColor',  // 文字颜色
            'backColor',  // 背景颜色
            'link',  // 插入链接
            'list',  // 列表
            'justify',  // 对齐方式
            'quote',  // 引用
            'emoticon',  // 表情
            'image',  // 插入图片
            'table',  // 表格
            'video',  // 插入视频
            'code',  // 插入代码
            'undo',  // 撤销
            'redo'  // 重复
        ]
        editor.customConfig.uploadImgShowBase64 = true
        editor.create()
    };

注意点一:
此处需要十分注意的是 editor.customConfig.menus 这个属性设置,这个属性是配置你的富文本编辑器所需要的功能的,如果不配置的话,那么界面就不会有上面的加粗斜体上传图片之类的功能条了,当然,如果你不需要这么多功能的话,也可以注释掉一部分。
注意点二:
editor.customConfig.uploadImgShowBase64 = true 这个属性是配置当前是否需要设置上传图片在前端转换成base64的,如果你当前对接的模式是需要先上传图片到自己的服务器上的话,那么请查看官方文档,文档内有相关代码:

    editor.customConfig.uploadImgServer = 'https://gtacms.gtarcade/backend/editor/index?action=uploadimage';  // 上传图片到服务器
    // 3M
    editor.customConfig.uploadImgMaxSize = 3 * 1024 * 1024;
    // 限制一次最多上传 5 张图片
    editor.customConfig.uploadImgMaxLength = 1;
    // 自定义文件名
    editor.customConfig.uploadFileName = 'editor_img';
    // 将 timeout 时间改为 3s
    editor.customConfig.uploadImgTimeout = 5000;

    editor.customConfig.uploadImgHooks = {
        before: function (xhr, editor, files) {
            // 图片上传之前触发
            // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,files 是选择的图片文件

            // 如果返回的结果是 {prevent: true, msg: 'xxxx'} 则表示用户放弃上传
            // return {
            //     prevent: true,
            //     msg: '放弃上传'
            // }
            // alert("前奏");
        },
        success: function (xhr, editor, result) {
            // 图片上传并返回结果,图片插入成功之后触发
            // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果
            // var url = result.data.url;
            // alert(JSON.stringify(url));
            // editor.txt.append(url);
            // alert("成功");
        },
        fail: function (xhr, editor, result) {
            // 图片上传并返回结果,但图片插入错误时触发
            // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象,result 是服务器端返回的结果
            alert("失败");
        },
        error: function (xhr, editor) {
            // 图片上传出错时触发
            // xhr 是 XMLHttpRequst 对象,editor 是编辑器对象
            // alert("错误");
        },
        // 如果服务器端返回的不是 {errno:0, data: [...]} 这种格式,可使用该配置
        // (但是,服务器端返回的必须是一个 JSON 格式字符串!!!否则会报错)
        customInsert: function (insertImg, result, editor) {
            // 图片上传并返回结果,自定义插入图片的事件(而不是编辑器自动插入图片!!!)
            // insertImg 是插入图片的函数,editor 是编辑器对象,result 是服务器端返回的结果
            // 举例:假如上传图片成功后,服务器端返回的是 {url:'....'} 这种格式,即可这样插入图片:
            var url = result.data[0];
            insertImg(url);
            // result 必须是一个 JSON 格式字符串!!!否则报错
        }
    }

好了,以上配置完毕就可以在前端进行使用了,咱们来看下效果:

完整代码

import React, { Component } from 'react';
import E from 'wangeditor'
//import { inject, observer } from 'mobx-react'
//import { withRouter } from 'react-router-dom'

//@withRouter @inject('appStore') @observer
class Editor extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            editorContent:''
         };
    }

    componentDidMount() {
        const elemMenu = this.refs.editorElemMenu;
        const elemBody = this.refs.editorElemBody;
        const editor = new E(elemMenu,elemBody)
        // 使用 onchange 函数监听内容的变化,并实时更新到 state 中
        editor.customConfig.onchange = html => {
            console.log(editor.txt.html())
            this.setState({
                // editorContent: editor.txt.text()
                editorContent: editor.txt.html()
            })
        }
        editor.customConfig.menus = [
            'head',  // 标题
            'bold',  // 粗体
            'fontSize',  // 字号
            'fontName',  // 字体
            'italic',  // 斜体
            'underline',  // 下划线
            'strikeThrough',  // 删除线
            'foreColor',  // 文字颜色
            'backColor',  // 背景颜色
            'link',  // 插入链接
            'list',  // 列表
            'justify',  // 对齐方式
            'quote',  // 引用
            'emoticon',  // 表情
            'image',  // 插入图片
            'table',  // 表格
            'video',  // 插入视频
            'code',  // 插入代码
            'undo',  // 撤销
            'redo'  // 重复
        ]
        editor.customConfig.uploadImgShowBase64 = true
        editor.create()

    };

    render() {
        return (
            <div className="shop">
                <div className="text-area" >
                    <div ref="editorElemMenu"
                         style={{backgroundColor:'#f1f1f1',border:"1px solid #ccc"}}
                         className="editorElem-menu">

                    </div>
                    <div
                        style={{
                            padding:"0 10px",
                            overflowY:"scroll",
                            height:300,
                            border:"1px solid #ccc",
                            borderTop:"none"
                        }}
                        ref="editorElemBody" className="editorElem-body">

                    </div>
                </div>
            </div>
        );
    }
}

export default Editor;

写在最后

以上就是如何在react项目中使用editor富文本编辑器的相关内容了。希望这篇文档能给您带来帮助,感谢阅读。

更多推荐

在react中使用富文本编辑器 react+wangeditor