likes
comments
collection
share

非常好用的json编译器jsoneditor

作者站长头像
站长
· 阅读数 9

前言

今天给大家介绍一个非常好用的json编译器,jsoneditor,它支持五种查看模式: code、树形、文本、表单、视图,满足日常的开发需求。

安装

npm i jsoneditor

使用

code模式

可以进行编辑

  const editorOptions: any = {
        mode: 'code', 
        history: true,
  };

非常好用的json编译器jsoneditor 输错了会有错误提示 非常好用的json编译器jsoneditor

树形模式

只能查看,右上角还可以搜索值

  const editorOptions: any = {
        mode: 'view', 
        history: true,
  };

非常好用的json编译器jsoneditor

文本模式

  const editorOptions: any = {
        mode: 'text', 
        history: true,
  };

非常好用的json编译器jsoneditor

隐藏工具栏

  const editorOptions: any = {
        mode: 'text', 
        history: true,
        mainMenuBar: false,
  };

非常好用的json编译器jsoneditor

表单模式

表单模式就是value值可以编辑,key值不能改,查看还是树形的结构,可以折叠。

  const editorOptions: any = {
        mode: 'form', 
        history: true,
  };

非常好用的json编译器jsoneditor

完整代码

react组件的封装

import JSONEditor from 'jsoneditor';
import 'jsoneditor/dist/jsoneditor.css';
import _ from 'lodash';
import {
  forwardRef,
  useCallback,
  useEffect,
  useImperativeHandle,
  useRef,
} from 'react';

type Props = {
  onChange?: (obj?: any) => void;
  value?: Record<string, any>;
  options?: Record<string, any>;
  height?: number;
};
export default forwardRef(
  ({ onChange = () => {}, value, options = {}, height = 400 }: Props, ref) => {
    const viewContainerRef = useRef<any>();
    const editorRef = useRef<any>();

    // 注意这边暴露到外面的是一个json
    const handleChange = useCallback(
      (value) => {
        try {
          const currenValue = value === '' ? null : editorRef.current.get();
          onChange(currenValue);
        } catch (err) {}
      },
      [onChange],
    );
    const onError = (errArr: any) => {
      console.log('errArr', errArr);
      // if (errArr.length > 0) {
      //   onChange(undefined);
      // }
    };
    useImperativeHandle(ref, () => ({
      editorRef: editorRef,
    }));

    useEffect(() => {
      const editorOptions: any = {
        mode: 'code', //可用值:'tree'(默认值)、'view'、'form'、'code'、'text'、'preview'
        history: true,
        onChangeText: handleChange,
        onValidationError: onError,
        // mainMenuBar: false, // 工具栏
        ...options,
      };
      if (!editorRef.current) {
        editorRef.current = new JSONEditor(
          viewContainerRef.current,
          editorOptions,
        );
      }
    }, [options]);

    // 监听外部传入的value
    useEffect(() => {
      try {
        // 深度比较两个值是否相等
        if (value && !_.isEqual(editorRef.current.get(), value)) {
          editorRef.current.update(value);
        }
      } catch (error) {
        // 当编辑器内容为空时,editorRef.current.get()会抛出异常,所以这里需要捕获
      }
    }, [value]);

    return (
      <div
        style={{ height: `${height}px` }}
        ref={(elem) => (viewContainerRef.current = elem)}
      />
    );
  },
);

其他的还有很多功能可以参考githup的文档

转载自:https://juejin.cn/post/7338250632938274825
评论
请登录