瀏覽代碼

react-panel: Clean up the JSONFormatter and make sure it updates both on mount and when props update

Johannes Schill 7 年之前
父節點
當前提交
5cca489acd
共有 1 個文件被更改,包括 25 次插入11 次删除
  1. 25 11
      public/app/core/components/JSONFormatter/JSONFormatter.tsx

+ 25 - 11
public/app/core/components/JSONFormatter/JSONFormatter.tsx

@@ -1,38 +1,52 @@
-import React, { PureComponent } from 'react';
-import JSONFormatterJS from 'json-formatter-js';
+import React, { PureComponent, createRef } from 'react';
+import JSONFormatterJS, { JSONFormatterConfiguration } from 'json-formatter-js';
 
 
 interface Props {
 interface Props {
   className?: string;
   className?: string;
-  json: any;
-  config?: any;
+  json: {};
+  config?: JSONFormatterConfiguration;
   open?: number;
   open?: number;
 }
 }
 
 
 export class JSONFormatter extends PureComponent<Props> {
 export class JSONFormatter extends PureComponent<Props> {
-  wrapperEl: any = React.createRef();
-  jsonEl: HTMLElement;
-  formatter: any;
+  private wrapperRef = createRef<HTMLDivElement>();
+  private formatter: any;
 
 
   static defaultProps = {
   static defaultProps = {
     open: 3,
     open: 3,
     config: {
     config: {
       animateOpen: true,
       animateOpen: true,
+      theme: 'dark',
     },
     },
   };
   };
 
 
   componentDidMount() {
   componentDidMount() {
+    this.renderJson();
+  }
+
+  componentDidUpdate() {
+    this.renderJson();
+  }
+
+  renderJson = () => {
     const { json, config, open } = this.props;
     const { json, config, open } = this.props;
     this.formatter = new JSONFormatterJS(json, open, config);
     this.formatter = new JSONFormatterJS(json, open, config);
-    this.jsonEl = this.wrapperEl.current.appendChild(this.formatter.render());
-  }
+    const wrapperEl = this.wrapperRef.current;
+    const newJsonHtml = this.formatter.render();
+    const hasChildren: boolean = wrapperEl.hasChildNodes();
+    if (hasChildren) {
+      wrapperEl.replaceChild(newJsonHtml, wrapperEl.lastChild);
+    } else {
+      wrapperEl.appendChild(newJsonHtml);
+    }
+  };
 
 
   componentWillUnmount() {
   componentWillUnmount() {
     this.formatter = null;
     this.formatter = null;
-    this.jsonEl = null;
   }
   }
 
 
   render() {
   render() {
     const { className } = this.props;
     const { className } = this.props;
-    return <div className={className} ref={this.wrapperEl} />;
+    return <div className={className} ref={this.wrapperRef} />;
   }
   }
 }
 }