Json输入vanilla-jsoneditor

一些后台项目中会用到json编辑,试了几个json编辑库,发现这个库比较好用;简单实现一个React的封装组件,考虑到vue3没有选择用官方提供组件,目前这种方式稍微换下api相对通用;

项目中依赖版本
"vanilla-jsoneditor": "^2.2.0",
封装react组件
import React, { useEffect, useRef, useState } from 'react';

import { createJSONEditor, JSONEditorPropsOptional  } from 'vanilla-jsoneditor/standalone.js'

interface PropsType {
    defaultValue: string | object,
    onVerification: (result: boolean, message: string) => void,
    onChange: (value: string) => void,
}
import style from './style.module.less';
const JSONEditorReact = ({onChange, onVerification, defaultValue}: PropsType) => {
    const refContainer = useRef<any>(null)
    let content: any = {
        text: undefined,
        json: {
        }
      }
    const editor = useRef<any>(null);
    useEffect(() => {
      editor.current = createJSONEditor({
            target: refContainer.current,
            props: {
              content,
              mode: 'text',
              onChange: (updatedContent: any, previousContent: any, { contentErrors, patchResult }: any) => {
                content.text = updatedContent.text;           
                // 返回最新的值
                onChange && onChange(updatedContent.text);
                handleVerification();
              }
            }
      })
      return () => {
        editor.current && editor.current.destroy();
      }
    }, [])
    const handleVerification = () => {
      if (editor.current) {
        Promise.resolve().then(() => {
          const tmp = editor.current.validate();
          if (typeof tmp === 'undefined') {
            onVerification && onVerification(true, '');
            return;
          }
          onVerification && onVerification(false, tmp.parseError.message || 'json格式错误');
        })
      }
    }
    useEffect(() => {
      if (editor.current) {
        // 赋值如果是字符串复制给text 如果是对象复制给json
        if (typeof defaultValue === 'string') {
          editor.current.set({text: defaultValue});
        } else {
          editor.current.set({json: defaultValue});
        }
        // 手动触发校验
        handleVerification();
      }
    }, [defaultValue]);
    return <div ref={refContainer} className={style.root}/>
  }
  
  export default JSONEditorReact

less

如果想自己做校验输入是否能通过,可以隐藏插件自身的校验提示

:global {
    .jse-message.jse-error.svelte-czprfx{
        display: none;
    }
    .jse-message.jse-success.svelte-czprfx{
        display: none;
    }
}
使用
import VanillaJSONEditor from '@/views/Components/VanillaJSONEditor';
	// 最新的输入
 	const currentValue = useRef('');
 	// 默认值
	const [jsonEditValue, setJsonEditValue] = useState({});
	// 展示错误
	const [jsonEditVer, setJsonEditVer] = useState({
	  result: false, message: ''
	});
	const handleJsonEditChange = (val: any) => {
	  currentValue.current = val;
	}
 	const handleJSonEditVeriChange = (result: boolean, message: string) => {
        jsonEditVer.message = message;
        jsonEditVer.result = result;
        setJsonEditVer({...jsonEditVer});
    }
return <>
	 <VanillaJSONEditor 
	 	onChange={handleJsonEditChange}
	 	onVerification=	{handleJSonEditVeriChange} 
	 	defaultValue={jsonEditValue}>
	 </VanillaJSONEditor>
     {
          !jsonEditVer.result && <div className={style.edit_ver_error_wrap}>
              <span >{jsonEditVer.message}</span>
          </div>
      }
</>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值