一些后台项目中会用到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>
}
</>