react封装jsoneditor

该文章展示了如何在React应用中安装和使用JSONEditor库,通过import导入并配置组件,处理如jsonValue、otherOpts、domId等参数,以实现JSON对象的查看、编辑功能。同时强调了使用DOMID避免元素冲突的重要性。
摘要由CSDN通过智能技术生成

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 = ''; // 防止添加多个jsoneditor
      const 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重复,对容器的赋值会出现问题,可能会导致数据渲染不对的情况
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值