天天看点

富文本编辑器--基于wangEditor富文本编辑器的改进与完善

做组里项目的时候,需要这样一个可以即插即用的富文本编辑器,在其他的项目里通过import方式可以直接使用,因为项目本身是用react写的,这个wangEditor富文本编辑器刚好可用于React项目,且页面看起来比较简洁清爽,故搬运过来作了些配置,完善了上传图片的功能,并添加了将输入文本内容转换为HTML格式和JSON格式的功能。

富文本编辑器--基于wangEditor富文本编辑器的改进与完善

1.按照wangEditor官网的提示,拉到代码之后,有以下一段文字指示你用于React:

富文本编辑器--基于wangEditor富文本编辑器的改进与完善

官网就是官网,提示都写的毫无营养。折腾了一下这里,从项目目录开始看起,看一下怎么用于React项目:

富文本编辑器--基于wangEditor富文本编辑器的改进与完善

教程里说的npm start启动wangEditor的方式只有在如图的项目目录下才可生效

2.项目应用:

import React, { Component } from 'react';
import E from 'wangeditor';
import './App.css';
import Card from "../../ishow/Card/index";
import Row from '../../ishow/LayoutComponent/row/index';
import Col from '../../ishow/LayoutComponent/col/index';
import Breadcrumb from '../../ishow/Breadcrumb/index';

class App extends Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            editorContent: '',
            editorContentJson: ''
        }
    }

    componentDidMount() {
        const elem = this.refs.editorElem
        const editor = new E(elem)
        const text1 = document.getElementById('text1')
        const text2 = document.getElementById('text2')
        const onUploadFile = (url, name, folder, type, style) => {
            return url + '?name=' + name + '&folder=' + folder + '&type=' + type + '&style=' + style;
        };

        editor.customConfig.uploadImgServer = 'http://10.10.33.144/filebroker/upload'

        editor.customConfig.customUploadImg = function (files, insert) {
            // files 是 input 中选中的文件列表
            // insert 是获取图片 url 后,插入到编辑器的方法
            let file;
            if (files && files.length) {
                file = files[0];
            } else {
                return
            }

            const uploadImgServer = "http://10.10.33.144/filebroker/upload";
            const xhr = new XMLHttpRequest();
            const test = onUploadFile(uploadImgServer, 'image.jpg', 'local', 0, 1);
            xhr.open('POST', test);
            const data = new FormData();
            data.append('image', file);
            xhr.send(data);
            xhr.addEventListener('load', () => {
                const response = JSON.parse(xhr.responseText);
                const imgUrl = response.data[0].local;
                insert(imgUrl)
            });
            xhr.addEventListener('error', () => {
                const error = JSON.parse(xhr.responseText);
                alert('上传失败');
            });
        }

        // 使用 onchange 函数监听内容的变化,并实时更新到 state 中
        editor.customConfig.onchange = (html, getJSON) => {
            var json = editor.txt.getJSON()
            this.setState({
                editorContent: html,
                editorContentJson: json
            })
            document.getElementById('text1').value = html
            document.getElementById('text2').value = JSON.stringify(json)//转换为JSON字符串
            console.log(JSON.stringify(json))
        }
        editor.create()//将生成编辑器
    }

    render() {
        const { editorContent } = this.state;
        return (
            <div className="App">
                <h2>富文本编辑器</h2>
                <Breadcrumb first="UI" second="富文本" />
                <div ref="editorElem" style={{ textAlign: 'left' }}>
                    <div className='div1'>
                    </div>
                </div>
                <Row>
                    <Col className="gutter-row" md={12} >
                        <Card style={{ borderStyle: 'none', boxShadow: '0px 0px 0px #888888' }}
                            header={
                                <div>
                                    <span style={{ lineHeight: '20px', fontSize: '16px', fontWeight: '600' }}>同步转换HTML</span>
                                </div>
                            }
                        >
                            <textarea id="text1" style={{ width: '100%', height: '100px', borderStyle: 'none' }}></textarea>
                        </Card>
                    </Col>
                    <Col className="gutter-row" md={12}>
                        <Card style={{ borderStyle: 'none', boxShadow: '0px 0px 0px #888888' }}
                            header={
                                <div>
                                    <span style={{ lineHeight: '20px', fontSize: '16px', fontWeight: '600' }}>同步转换JSON</span>
                                </div>
                            }>
                            <textarea id="text2" style={{ width: '100%', height: '100px', borderStyle: 'none' }}></textarea>
                        </Card>
                    </Col>
                </Row>
            </div>
        );
    }
}

export default App;
           

主要涉及的是两个地方的改动:

1,本地图片上传

上传地址拼接方法:

const onUploadFile = (url, name, folder, type, style) => {
            return url + '?name=' + name + '&folder=' + folder + '&type=' + type + '&style=' + style;
        };

        editor.customConfig.uploadImgServer = 'http://10.10.33.144/filebroker/upload'
           

图片上传实现:

editor.customConfig.customUploadImg = function (files, insert) {
            // files 是 input 中选中的文件列表
            // insert 是获取图片 url 后,插入到编辑器的方法
            let file;
            if (files && files.length) {
                file = files[0];
            } else {
                return
            }

            const uploadImgServer = "http://10.10.33.144/filebroker/upload";
            const xhr = new XMLHttpRequest();
            const test = onUploadFile(uploadImgServer, 'image.jpg', 'local', 0, 1);
            xhr.open('POST', test);
            const data = new FormData();
            data.append('image', file);
            xhr.send(data);
            xhr.addEventListener('load', () => {
                const response = JSON.parse(xhr.responseText);
                const imgUrl = response.data[0].local;
                insert(imgUrl)
            });
            xhr.addEventListener('error', () => {
                const error = JSON.parse(xhr.responseText);
                alert('上传失败');
            });
        }
           

图片上传可参考formdata表单提交的方式,点击打开链接

imgUrl是从后台拿到的图片的地址,insert是从后台拿到url后将图片插入到编辑器中的方法。

2.将编辑输入内容转换为HTML和JSON数据格式

给定初始状态:

this.state = {
            editorContent: '',
            editorContentJson: ''
        }
           

通过获取id的方式两个编辑区域:

const text1 = document.getElementById('text1')
 const text2 = document.getElementById('text2')
           

编辑内容格式转换方法:

editor.customConfig.onchange = (html, getJSON) => {
            var json = editor.txt.getJSON()
            this.setState({
                editorContent: html,
                editorContentJson: json
            })
            document.getElementById('text1').value = html
            document.getElementById('text2').value = JSON.stringify(json)//转换为JSON字符串
        }
        editor.create()//将生成编辑器
    }
           

text1和text2对应的分别是如下两部分的编辑区域:

富文本编辑器--基于wangEditor富文本编辑器的改进与完善

将两个编辑区域的内容格式分别定义为html和json格式(json格式需要做一步转换字符串操作: JSON.stringfy());

因为这个富文本编辑器是集成到公司项目作为一个组件来用的,所以如Card这样的组件都是直接import完了直接用的,一些依赖也是直接通过yarn install方法获取的,还未完全将其抽离出来做成组件,这款富文本编辑器还有很多值得深究的地方,以后有时间再研究。