simditor是一个依赖于JQuery富文本编辑器的模块,需要先安装jQuery之后再引入到项目中使用
使用方法
- 使用
npm install simditor@2.3.6
或者yarn add simditor@2.3.6
这里推荐安装2.3.6版本,笔者在使用的时候安装最新版本会在运行时报错(如果在您的项目中没有报错可以直接安装最新版本) - 新建一个富文本编辑器的通用模块放入以下代码
import React, { Component } from 'react'
import Simditor from 'simditor';
import 'simditor/styles/simditor.scss'
// 通用的富文本编辑器,依赖于jQuery
class RichEditor extends Component {
constructor(props) {
super(props)
this.state = {}
}
componentDidMount(){
this.loadEditor()
}
loadEditor(){
let element = this.refs['textarea'];
this.simditor = new Simditor({
textarea:$(element),
defaultValue:this.props.placeholder || '请输入内容',
upload: {
// 对应后端接口
url:'/manage/product/richtext_img_upload.do',
defalutImage:'',
// 对应后端接口的字段名称
fileKey:'upload_file'
}
})
this.bindEditorEvent()
}
// 初始化富文本编译器事件
bindEditorEvent(){
this.simditor.on('valuechanged',e=>{
this.props.onValueChange(this.simditor.getValue())
})
}
render() {
return (
<div className="rich-editor">
<textarea ref="textarea"></textarea>
</div>
)
}
}
export default RichEditor
- 在需要使用的文件中引入该模块并传入一个监听内容变化的函数
import React, { Component } from 'react'
import RichEditor from 'util/rich-editor/index.jsx'
class ProductSave extends Component {
constructor(props) {
super(props)
this.state = {}
}
// 富文本编辑器变化
onDetailValueChange(value){
console.log(value)
this.setState({
detail: value
})
}
render() {
return (
<div>
// xxxxx
<RichEditor onValueChange={value=>{this.onDetailValueChange(value)}}/>
// xxxxx
</div>
)
}
}
export default ProductSave
相关参数和API
simditor的参数和api很多,这里只介绍常用的,详细参数和api见官方文档
- 在
new Simditor
时传入的参数
// 需要替换成富文本编辑器的textarea元素
textarea:$(element),
// 默认值
defaultValue:this.props.placeholder || '请输入内容',
// 上传的相关参数
upload: {
// 对应后端接口
url:'/manage/product/richtext_img_upload.do',
defalutImage:'',
// 对应后端接口的字段名称
fileKey:'upload_file'
}
new Simditor
的相关api
// 创建一个Simditor
this.simditor = new Simditor(params)
// 添加监听
this.simditor.on('valuechanged',callback)
// 获取文本内容(html结构)
this.simditor.getValue()
// 回传值
this.simditor.setValue(value)