react CKEditor Demo

在實際項目中需要使用富文本編輯器,由于react-draft-wysiwyg富文本組件沒有給我提供表格的功能(后期我有空研究一下draft-js-table),則使用更快速實現功能的ckeditor

// index.html直接引入 或者 動態加載 
<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(){
// 當該組件用于創建模塊時,需要渲染editor(條件:我之前從沒初始化過)
      if (this.props.content === '' && this.props.id && this.state.init === false) {
        this.loadCkEditor(this.props);
      }
    }

// 每次更新都會走進該周期,我需要判斷有沒有初始化過 && 外部有傳進內容
// 當沒有init===false的判斷,會導致頁面渲染多個編輯器,我頭開始的解決方案不是用init作為標記,而是使用ckeditor的destory 、delete等方法,發現實現起來都不太干凈,且有問題
    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

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。