简单介绍:
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;
}