在實(shí)際項(xiàng)目中需要使用富文本編輯器,由于react-draft-wysiwyg富文本組件沒(méi)有給我提供表格的功能(后期我有空研究一下draft-js-table),則使用更快速實(shí)現(xiàn)功能的ckeditor
// index.html直接引入 或者 動(dòng)態(tài)加載
<script src="http://cdn.ckeditor.com/4.7.1/full/ckeditor.js"></script>
import CKEditor from "../../components/CKEditor.jsx";
<CKEditor
id="content"
content={this.props.contractBodyEditor}
onChange={(value) => this.ckOnChange(value)}/>
import React, { Component } from 'react';
class CKEditor extends Component {
constructor(props) {
super(props);
this.elementName = "editor_" + props.id;
this.state = {
init: false
}
}
componentDidMount(){
// 當(dāng)該組件用于創(chuàng)建模塊時(shí),需要渲染editor(條件:我之前從沒(méi)初始化過(guò))
if (this.props.content === '' && this.props.id && this.state.init === false) {
this.loadCkEditor(this.props);
}
}
// 每次更新都會(huì)走進(jìn)該周期,我需要判斷有沒(méi)有初始化過(guò) && 外部有傳進(jìn)內(nèi)容
// 當(dāng)沒(méi)有init===false的判斷,會(huì)導(dǎo)致頁(yè)面渲染多個(gè)編輯器,我頭開(kāi)始的解決方案不是用init作為標(biāo)記,而是使用ckeditor的destory 、delete等方法,發(fā)現(xiàn)實(shí)現(xiàn)起來(lái)都不太干凈,且有問(wèn)題
componentWillReceiveProps(nextProps) {
if (CKEDITOR && nextProps && nextProps.content && nextProps.id && this.state.init === false) {
this.loadCkEditor(nextProps);
}
}
loadCkEditor = (nextProps) => {
this.elementName = "editor_" + this.props.id;
CKEDITOR.replace(this.elementName);
const { onChange } = nextProps;
CKEDITOR.instances[this.elementName].on("change", function () {
onChange && onChange(CKEDITOR.instances[this.elementName].getData())
}.bind(this));
this.setState({
init: true
})
}
render() {
return (
<textarea ref="content1" name={this.elementName} value={this.props.content ? this.props.content : ''}></textarea>
)
}
}
export default CKEditor