美文网首页
react CKEditor Demo

react CKEditor Demo

作者: Ann_l | 来源:发表于2019-04-28 16:51 被阅读0次

在实际项目中需要使用富文本编辑器,由于react-draft-wysiwyg富文本组件没有给我提供表格的功能(后期我有空研究一下draft-js-table),则使用更快速实现功能的ckeditor

// index.html直接引入 或者 动态加载 
<script src="//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

相关文章

网友评论

      本文标题:react CKEditor Demo

      本文链接:https://www.haomeiwen.com/subject/vtljnqtx.html