救命啊!ueditor富文本框销毁重建后陷入死循环

ueditor第一次渲染正常,但是第二次渲染不出来,然后通过百度知道,二次渲染的话,要先对其进行destroy销毁,但是,销毁之后,ueditor进入UE.Editor.prototype.getActionUrl = function (action) {}那个方法就死循环。

实例化ueditor代码

import React, { PureComponent } from 'react';

import { domain_api } from '@/utils/utils'

export default class Editor extends PureComponent {
  state = {
    content: this.props.content,
  }

  componentDidMount() {
    console.log('===================componentDidMount=========================',this.props.content) 
    this.loadUEditor(true);
  }
  loadUEditor = (load) => {
    console.log('==================loadUEditor============================',load)
    //再次初始化有问题  要销毁原来的
   
    const CALLBACK = this.call_back_content;
    const RELOAD = this.loadUEditor;
    /*     =========== ueditor2.js =============      */

    function launchFullscreen(a) {
      console.log('launchFullscreen',a)
      if (a.requestFullscreen) {
        a.requestFullscreen();
      } else {
        if (a.mozRequestFullScreen) {
          a.mozRequestFullScreen()
        } else {
          if (a.msRequestFullscreen) {
            a.msRequestFullscreen()
          } else {
            if (a.webkitRequestFullscreen) {
              a.webkitRequestFullScreen()
            }
          }
        }
      }
    }
    function exitFullscreen() {
      if (document.exitFullscreen) {
        document.exitFullscreen()
      } else {
        if (document.mozCancelFullScreen) {
          document.mozCancelFullScreen()
        } else {
          if (document.webkitExitFullscreen) {
            document.webkitExitFullscreen()
          }
        }
      }
    }
    function fullscreenElement() {
      return document.fullscreenElement || document.webkitCurrentFullScreenElement || document.mozFullScreenElement || null
    }
    /*!  */
    $(function () {
      console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
      var a = new ZeroClipboard($(".copywx"));
      $("#mask").size() >= 1 && $("#mask").height($("body").height()), $(".colorshow").on("click", function () {
        "block" == $("#colorpickerbox").css("display") ? ($("#colorpickerbox").slideUp(), $(".content").height($(".content").height() + 195)) : ($("#colorpickerbox").slideDown(), $(".content").height($(".content").height() - 195))
      }), $("#phoneclose").on("click", function () {
        $("#previewbox").hide()
      }), $(".xphone").on("click", function () {
        "block" == $("#previewbox").css("display") ? $("#previewbox").hide() : $("#previewbox").show()
      }), $(window).on("fullscreenchange webkitfullscreenchange mozfullscreenchange", function () {
        fullscreenElement() || $(".wxeditor").css({margin: "10px 0 0 0"})
      }), $(".fullshowbox").on("click", function () {
        $(".wxeditor").css({margin: "50px 0"}), launchFullscreen(document.documentElement)
      }), $(".fullhidebox").on("click", function () {
        $("#wxeditortip,#header").show(), exitFullscreen()
      });
      var b = ["borderTopColor", "borderRightColor", "borderBottomColor", "borderLeftColor"], c = [];
      $.each(b, function (a) {
        c.push(".itembox .wxqq-" + b[a])
      }), $("#colorpickerbox").ColorPicker({
        flat: !0, color: "#f54242", onChange: function (a, d) {
          $(".itembox .wxqq-bg").css({backgroundColor: "#" + d}), $(".itembox .wxqq-color").css({color: "#" + d}), $.each(c, function (a) {
            $(c[a]).css(b[a], "#" + d)
          })
        }
      });
      // UE.delEditor('editor');
      var d = UE.getEditor("editor", {
        topOffset: 0,
        //autoFloatEnabled: !1,
        // autoHeightEnabled: !1,
        autotypeset: {removeEmptyline: !0},
        toolbars: [["source", "undo", "redo", "bold", "italic", "underline", "forecolor", "backcolor", "link", "unlink", "paragraph", "fontfamily", "fontsize",],
          ["indent", "justifyleft", "justifyright", "justifycenter", "justifyjustify", "rowspacingtop", "rowspacingbottom", "lineheight", "edittip ", "inserttable", 'drafts', "emotion", "map", "insertimage", "insertvideo", "music", "searchreplace", "removeformat", "autotypeset",],
          ["fullscreen",]],
        autoHeightEnabled: false,
        allowDivTransToP: false,
        autoFloatEnabled: false,
        enableAutoSave: true
      })
      // config upload
      UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
      console.log('xxxxxxxxxxxxxxxxxxxxxxxxxxxx',UE.Editor.prototype._bkGetActionUrl)
      UE.Editor.prototype.getActionUrl = function (action) {
        console.log('getActionUrl',action)
        if (action == 'uploadimage' || action == 'uploadscrawl' || action == 'uploadvideo' || action == "uploadfile") {
          console.log('上传文件')
          return `${domain_api}/ueditor/upload/image`;//此处写自定义的图片上传路径
        } else {
          console.log('elseelseelseelseelseelseelseelseelseelseelseelseelseelseelseelseelseelseelseelseelseelse',this._bkGetActionUrl.call(this, action))
          return this._bkGetActionUrl.call(this, action);
        }
      }
      // config upload - end

      // $(function(){var a=new ZeroClipboard($(".copywx"));$("#mask").size()>=1&&$("#mask").height($("body").height()),$(".colorshow").on("click",function(){"block"==$("#colorpickerbox").css("display")?($("#colorpickerbox").slideUp(),$(".content").height($(".content").height()+195)):($("#colorpickerbox").slideDown(),$(".content").height($(".content").height()-195))}),$("#phoneclose").on("click",function(){$("#previewbox").hide()}),$("#phone").on("click",function(){"block"==$("#previewbox").css("display")?$("#previewbox").hide():$("#previewbox").show()}),$(window).on("fullscreenchange webkitfullscreenchange mozfullscreenchange",function(){fullscreenElement()||$(".wxeditor").css({margin:"10px 0 0 0"})}),$(".fullshowbox").on("click",function(){$(".wxeditor").css({margin:"50px 0"}),launchFullscreen(document.documentElement)}),$(".fullhidebox").on("click",function(){$("#wxeditortip,#header").show(),exitFullscreen()});var b=["borderTopColor","borderRightColor","borderBottomColor","borderLeftColor"],c=[];$.each(b,function(a){c.push(".itembox .wxqq-"+b[a])}),$("#colorpickerbox").ColorPicker({flat:!0,color:"#f54242",onChange:function(a,d){$(".itembox .wxqq-bg").css({backgroundColor:"#"+d}),$(".itembox .wxqq-color").css({color:"#"+d}),$.each(c,function(a){$(c[a]).css(b[a],"#"+d)})}});var d=UE.getEditor("editor",{topOffset:0,autoFloatEnabled:!1,autoHeightEnabled:!1,autotypeset:{removeEmptyline:!0},toolbars:[["source","undo","redo","bold","italic","underline","forecolor","backcolor","link","unlink","paragraph","fontfamily","fontsize",],["indent","justifyleft","justifyright","justifycenter","justifyjustify","rowspacingtop","rowspacingbottom","lineheight","edittip ","inserttable","template",'drafts',"emotion","map","insertvideo","spechars","searchreplace","removeformat","autotypeset",]],autoHeightEnabled: false,allowDivTransToP: false,autoFloatEnabled: false,enableAutoSave: true});
      d.addListener("click", function (t, evt) {

        evt = evt || window.event;
        var el = evt.target || evt.srcElement;
        if (el.tagName == "IMG") {
          return;
        }
        if ($(el).parents('.unieditor').size() > 0) {
          el = $(el).parents('.unieditor:first').get(0);
          if (current_active_v3item) {
            current_active_v3item.removeAttr('style');
          }
          current_active_v3item = $(el);
          current_active_v3item.css({
            'border': '1px dotted rgb(255, 68, 1)',
            'padding': '2px'
          });
          clickPop.render();
          var html = clickPop.formatHtml('<nobr class="otf-poptools">' + '<span onclick="$$.select()" stateful>' + '选中</span>' + '<span onclick="$$._remove()" stateful>' + '删除</span>' + '<br/><span onclick="$$._blank()" stateful>' + '后空行</span>' + '<span onclick="$$._preblank()" stateful>' + '前空行</span>' + '</nobr>');
          var content = clickPop.getDom('content');
          content.innerHTML = html;
          clickPop.anchorEl = el;
          clickPop.showAnchor(clickPop.anchorEl);
          var client = new ZeroClipboard($(clickPop.getDom('content')).find('.copy'));
          client.on('ready', function (event) {
            client.on('copy', function (event) {
              $(clickPop.anchorEl).removeAttr('style');
              event.clipboardData.setData('text/html', $(clickPop.anchorEl).prop('outerHTML'));
              clickPop.hide();
              showSuccessMessage("已成功复制到剪切板");
            });
          });
          var cut_client = new ZeroClipboard($(clickPop.getDom('content')).find('.cut'));
          cut_client.on('ready', function (event) {
            cut_client.on('copy', function (event) {
              $(clickPop.anchorEl).removeAttr('style');
              event.clipboardData.setData('text/html', $(clickPop.anchorEl).prop('outerHTML'));
              clickPop.hide();
              $(clickPop.anchorEl).remove();
              showSuccessMessage("已成功剪切到剪切板");
            });
          });
        }
        else {
          if (current_active_v3item) {
            current_active_v3item.removeAttr('style');
            current_active_v3item = null;
          }
        }
      });
      var clickPop = new baidu.editor.ui.Popup({
        content: "", editor: d, _remove: function () {
          $(clickPop.anchorEl).remove();
          clickPop.hide();
        }, _copy: function () {
          $(clickPop.anchorEl).prop('outerHTML');
          clickPop.hide();
        }, select: function () {
          var range = d.selection.getRange();
          range.selectNode(clickPop.anchorEl);
          range.select();
        }, _blank: function () {
          $('<p><br/></p>').insertAfter(clickPop.anchorEl);
        }, _preblank: function () {
          $('<p><br/></p>').insertBefore(clickPop.anchorEl);
        }, _video: function () {
          d.ui._dialogs['insertvideoDialog'] && d.ui._dialogs['insertvideoDialog'].open();
          d.ui._dialogs['insertvideoDialog'].anchorEl = clickPop.anchorEl;
        }, className: 'edui-bubble'
      });
      d.ready(function () {
        try{
          CALLBACK(d); // 初始化赋值
          console.log('================dddddddddddddddddddddddddddddd====================',d.getContent())
          $("#preview").html(d.getContent())
        } catch (e){
          // do nothing
          // console.log(e)
          // if(load){
          //   RELOAD(false)
          // }
        }
        console.log('ddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd',d,d.getContent())
        a.on("copy", function (a) {
          var b = a.clipboardData;
          b.setData("text/html", d.getContent()), alert("恭喜成功复制!在微信公众平台粘贴即可!")
        }), d.addListener("contentChange", function () {
          // $("#preview").html(d.getContent() + '<div><a style="font-size:12px;color:#607fa6" id="post-user">阅读原文</a> <em style="color:#8c8c8c;font-style:normal;font-size:12px;">阅读 100000+</em></div>')
          console.log('addListeneraddListeneraddListeneraddListeneraddListeneraddListeneraddL')
          $("#preview").html(d.getContent())
        }), $(".itembox").on("click", function () {
          d.execCommand("insertHtml", '<section class="unieditor">' + $(this).html() + "</section><br />")
        })
      }), $(".tabs li a").on("click", function () {
        $(this).addClass("current").parent().siblings().each(function () {
          $(this).find("a").removeClass("current")
        }), $("#" + $(this).attr("tab")).show().siblings().hide()
      }), $(".itembox img,.itembox audio").each(function () {
        var a = $(this);
        a.attr("src", a.data("src"))
      })
    });

    var current_active_v3item = null;
    ZeroClipboard.config({swfPath: "ueditor/third-party/zeroclipboard/ZeroClipboard.swf"});
    var client = new ZeroClipboard($('.copy-editor-html'));
    $(function () {
      $(window).resize(function () {
        var area_height = $(window).height();

        $('#editor,.edui-editor-iframeholder').height(area_height - 16);
        $('#styleselect').height(area_height);
        $('.content').height(area_height + 64);
      }).trigger('resize');

    });
  }

  getContent = () => {
    var previewDiv = document.getElementById("preview");
    return previewDiv.innerHTML;
  }

  call_back_content = (ref) => {
    console.log('call_back_contentcall_back_contentcall_back_contentcall_back_content',ref,this.props.callback)
    if(this.props.callback != undefined)
      this.props.callback(ref);
  }

  render() {
    return (
      <div className="wxeditor">
        <div className="clearfix">
       
          <div className="right">
            <div id="bdeditor" >
              <textarea id="editor" style={{ height:'auto' }} type="text/plain">
              </textarea>
            </div>
          </div>
          <div id="previewbox">
            <div style={{height: '100%', paddingRight: 5, msOverflowY: 'scroll'}}>
              <div style={{lineHeight: '24px', fontSize: 15, fontWeight: 700}}>战国科技</div>
              <div><em style={{color: 'rgb(140, 140, 140)', fontSize: 12, fontStyle: 'normal'}}>2020-02-02</em> <a
                id="post-user" style={{color: 'rgb(96, 127, 166)', fontSize: 12}} target="_blank">战国科技</a></div>
              <style
                dangerouslySetInnerHTML={{__html: "\n                {/*video, audio, img {*/}\n                {/*max - width: 100%*/}\n              {/*}*/}\n              "}}/>
              <div id="preview" style={{height: 292, overflowY: 'scroll'}}/>
            </div>
            <div id="phoneclose" style={{
              top: 30,
              width: 50,
              height: 50,
              right: 0,
              fontSize: 20,
              fontWeight: 700,
              position: 'absolute',
              cursor: 'pointer'
            }}>
              x
            </div>
          </div>
        </div>
      </div>
    );
  }
}

销毁的代码

      if(typeof(UE.getEditor("editor")) !='undefined'){
         UE.getEditor("editor").destroy(); 
        // UE.delEditor('editor')
      }

二次渲染的截图

clipboard.png

搞了几天,救命啊啊啊啊啊

阅读 4.2k
1 个回答
新手上路,请多包涵

第一个的时候会赋值为你自定义请求地址 然后一直递归

if(UE.Editor.prototype._bkGetActionUrl)return;
UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
加个判断

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题