react中引入wangEditor富文本编辑器

2020-05-08  本文已影响0人  pay_load

wangEditor是一款超轻量级的富文本编辑器,能满足大多数的开发需求,那么具体如何在react项目中使用呢?

1、导入wangEditor包

npm install wangeditor --save

2、页面引入wangEditor包

import E from 'wangeditor'

3、创建render函数

<div>
         <div ref="editorElemMenu"
                style={{ backgroundColor: '#f1f1f1',border: "1px solid #ccc", 
                   width: this.state.width >= 1300 ? "960px" : "800px", }}>
         </div>
         <div
           style={{
                   width: this.state.width >= 1300 ? "960px" : "800px",
                   height: 600,
                   border: "1px solid #ccc",
                   borderTop: "none",
                   zIndex: 20
                 }}
            ref="editorElemBody" >
               {/* 初始化富文本 (可直接为空什么也不写)*/}
               {this.props.location.state ?
                   <div dangerouslySetInnerHTML={{ __html: this.props.location.state.data.content }}>
                   </div>
                    : 
                   <div></div>
}
          </div>
</div>

4、初始化文本

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

5、在组件渲染完毕(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.customConfig.uploadImgHeight = 'auto';
        editor.create()
    };

*如遇到图片大小无法自适应的情况

设置高度  height:auto
document.getElementById('con').innerHTML = data[o].content
document.getElementById('con').style.height = 'auto'
上一篇下一篇

猜你喜欢

热点阅读