wangeditor(配合antd)的使用

10 篇文章 0 订阅
3 篇文章 0 订阅

简单介绍:
wangeditor
轻量级 web 富文本编辑器,配置方便,使用简单。支持 IE10+ 浏览器
antd
UI框架


使用(react):

npm install wangeditor

创建一个div元素作为编辑器的载体

import React, { Component, createRef } from 'react'
import E from 'wangeditor'

class Edit extends Component {
    constructor() {
        super()
        this.editorRef = createRef()
    }
    
	initEditor = () => {
        this.editor = new E(this.editorRef.current)
        this.editor.create()
    }
    
	componentDidMount() {
        this.initEditor()   
    }
    
    
    render() {
        return (
            <div className='rich-text-field' ref={this.editorRef}></div>
        )
	}
}

获取富文本内输入的内容:

// 将initEditor改写
initEditor = () => {
	this.editor = new E(this.editorRef.current)
	this.editor.customConfig.onchange= (html) => {
		console.log(html)	// html为拿到的在div富文本框中输入的内容(使用样式时会自动带上标签)
		// 如:<p><span style="font-weight: bold;">演示<span style="color: rgb(249, 150, 59);">文本</span></span></p>
	}
	this.editor.create()
}

提交数据:

一般将该富文本框放置于表单中时,需要将数据提交上表单需要再做一些额外操作:

从文本框中取得输入的数据→表单获取到数据→表单将该数据设定为提交内容某个key的值,否则表单可能无法获取到文本框内容

以配合使用antd为例:

import React, { Component, createRef } from 'react'
import {Form, Input} from 'antd'
import E from 'wangeditor'

class Edit extends Component {
    constructor() {
        super()
        this.editorRef = createRef()	
        this.formRef=createRef()
    }
    
    initEditor = () => {
        this.editor = new E(this.editorRef.current)
        this.editor.customConfig.onchange= (html) => {
            // antd表单通过name寻找到对应的表单元素,内置setFieldsValue()方法将该元素在表单中的value设置为对内容
            this.formRef.current.setFieldsValue({	 
                content:html
            })
        }
        this.editor.create()
    }

    componentDidMount() {
        this.initEditor()   
    }

 	render() {
        return (
        	<Form ref={this.formRef}>	{/* Form需要绑定ref,通过ref.current寻找到内置方法 */}
            	<Form.Item name='content'> {/* Form通过name属性寻找到指定表单元素 */}
                	<div className='rich-text-field' ref={this.editorRef} ></div>
                </Form.Item>
            </Form>
        )
    }
}

设置数据:

通过ref.txt.html()设置编辑框的显示文本

this.editorRef.text.html('要设置的文本')

css配置:

可能会出现上边栏不会自动换行的情况,

/* 这个类是自己生成的 */
.w-e-toolbar {
    flex-wrap:wrap;
}

如果发现富文本框z-index太高会挡住其他元素时

.rich-text-field {
    position:'relative';
    z-index:0;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值