React富文本编辑器的简单使用(wangeditor)
- 首先是安转:npm i wangeditor --save
- 在需要的文件中引人,但是这里最好使用组件话开发,这样在使用时只需要引入即可(注意这里只是简单的实现部分内容,从而添加到数据库之中)
- 创建一个单独的文件夹,在index.jsx中引入 import editor from “wangeditor”
简单实现文本输入、颜色、字体大小等文本的配置
import React, { Component } from 'react'
//引入react模块
import Editor from 'wangeditor'
//引入富文本编辑器
export default class index extends Component {
//这里使用的是类组件的形式封装
state = {
editor: null,
//设置状态,以便于之后的设置动态更新视图
num: Math.ceil(Math.random()*100)
//这里设置一个随机数,在之后创建的实例的时候拼接id方便在同一个文件中创建多个编辑器
}
componentDidMount(){
//在挂载结束之后配置相关参数,在这个生命周期中可以获取到页面中的元素和数据,
let { height = 300,full = false} = this.props
//在这里把要变更的参数解构出来方便之后的使用
let editor = new Editor(`#editor-${this.state.num}`)
//设置编辑器的高度
editor.config.height = height
//设置菜单
editor.config.menus = [
head ? 'head' : '',
emo ? 'emoticon' : '',
img ? 'image' : '',
//这里还可以设置如下的菜单项
/*
[
'head',
'bold',
'fontSize',
'fontName',
'italic',
'underline',
'strikeThrough',
'indent',
'lineHeight',
'foreColor',
'backColor',
'link',
'list',
'todo',
'justify',
'quote',
'emoticon',
'image',
'video',
'table',
'code',
'splitLine',
'undo',
'redo'
]
*/
]
// 配置全屏功能按钮是否展示
editor.config.showFullScreen = full
// 配置 onchange 回调函数
editor.config.onchange = (newHtml) => {
// console.log("change 之后最新的 html", newHtml);
if(this.props.onChange){
//判断使用组件时,是否设置这个事件,当不设置是会报错,这样避免了不必要的报错
this.props.onChange(newHtml)
//触发组件中的onChange事件,并进行传值
}
};
this.setState({
editor
//将配置好的编辑器设置到state中
},()=>{
this.state.editor.create()
//创建这个编辑器
})
}
render() {
return (
<div id={`editor-${this.state.num}`}> </div>
//富文本编辑器的挂载点
)
}
}
实现图片的上传
editor.config.uploadImgServer = `${this.serverIP}/upload/img`;
//设置图片文件上传的地址
editor.config.uploadFileName = "mainPic";
//设置图片文件的上传文件名
editor.config.zIndex = 0;
//设置富文本编辑器的层级
editor.config.uploadImgHooks = {
// 图片上传并返回了结果,想要自己把图片插入到编辑器中
// 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式,可使用 customInsert
customInsert: function(insertImgFn, result) {
console.log('customInsert', result)
//result是图片的地址
// insertImgFn 可把图片插入到编辑器,传入图片 src ,执行函数即可
insertImgFn(`http://localhost:3001${result.file}`);
//将图片插入到富文本编辑器中
//这里的地址需要之后自己更改
}
},