react-json-tree:只能做树级结构展示
react-json-editor-ajrm: 存在复制,会复制多项bug
jsoneditor:json编辑最佳解决方案
参考:https://blog.csdn.net/weixin_42391485/article/details/1126669...^v43^control&spm=1001.2101.3001.4242.2&utm_relevant_index=4

引入:npm install jsoneditor

react中创建 jsoneditor组件

import React, { useEffect, useRef } from 'react';
import JSONEditor from 'jsoneditor';
import 'jsoneditor/dist/jsoneditor.css';

const JSONEditorComponent = ({ json, onChange }) => {
  const editorRef = useRef(null);
  const containerRef = useRef(null);

  useEffect(() => {
    const options = {
      mode: 'tree', // or 'view', 'form', 'code', 'text', etc.
      onChange: () => {
        if (editorRef.current) {
          const updatedJson = editorRef.current.get();
          onChange(updatedJson);
        }
      },
    };
    
    if (containerRef.current) {
      editorRef.current = new JSONEditor(containerRef.current, options);
      editorRef.current.set(json);
    }
    
    return () => {
      if (editorRef.current) {
        editorRef.current.destroy();
      }
    };
  }, [json, onChange]);

  return <div ref={containerRef} style={{ height: '400px' }} />;
};

export default JSONEditorComponent;

组件中引入和使用

import React, { useState } from 'react';
import JSONEditorComponent from './JSONEditorComponent';

const App = () => {
  const [json, setJson] = useState({
    name: "John Doe",
    age: 30,
    address: {
      city: "New York",
      country: "USA"
    }
  });

  const handleJsonChange = (updatedJson) => {
    setJson(updatedJson);
  };

  return (
    <div>
      <h1>JSON Editor in React</h1>
      <JSONEditorComponent json={json} onChange={handleJsonChange} />
      <pre>{JSON.stringify(json, null, 2)}</pre>
    </div>
  );
};

export default App;

很白的小白
145 声望125 粉丝