1、安装:
api文档:jsoneditor
npm install jsoneditor
2、代码:
JsonEditor/index.tsx:
import { useMemoizedFn } from 'ahooks';
import JSONEditor from 'jsoneditor';
import { useEffect, useState } from 'react';
import './index.less';interface Props {jsonValue: any; // 需要渲染的json对象otherOpts?: any; // 其他配置项domId?: string; // 提供一个domid,避免同一个页面使用多个jsoneditor时,元素id重复,对容器的赋值会出现问题,可能会导致数据渲染不对的情况isExpandAll?: boolean; // 是否展开全部,默认不展开containerStyle?: any; // 容器样式,需要给一个宽高,不然可能会看不到jsoneditor
}export default function JsonEditor(props: Props) {const { jsonValue, otherOpts = {}, domId = 'jsoneditor', isExpandAll, containerStyle } = props;const [jsonRef, setJsonRef] = useState<any>(null);let editor: any;const renderJsonEditor = useMemoizedFn(() => {const container = document.getElementById(domId);if (container) {container.innerHTML = ''; // 防止添加多个jsoneditorconst options: any = {mode: 'view',modes: ['code', 'text', 'tree', 'view'],language: 'en',...otherOpts,};editor = new JSONEditor(container, options);editor.set(jsonValue);if (isExpandAll) {editor.expandAll();}}});useEffect(() => {renderJsonEditor();return () => {editor?.destroy();};}, [jsonRef, renderJsonEditor, jsonValue, editor]);return <div style={containerStyle} ref={setJsonRef} id={domId} />;
}
JsonEditor/index.less:
div.jsoneditor-field,
div.jsoneditor-value {cursor: pointer;
}
效果图:
注意:
- 提供一个domid,避免同一个页面使用多个jsoneditor时,元素id重复,对容器的赋值会出现问题,可能会导致数据渲染不对的情况