1、查阅资料,导师封装了这个组件
import React, { useCallback, useEffect, useRef } from 'react';
import _ from 'lodash';
import JSONEditor from 'jsoneditor';
import 'jsoneditor/dist/jsoneditor.css';
import styles from './index.less';
const SMJsonEditor = props => {
const { value, onChange, options = {} } = props;
const editorRef = useRef();
const editorObj = useRef();
// 注意这边暴露到外面的是一个json
const handleChange = useCallback(
value => {
try {
const currenValue = value === '' ? null : editorObj.current.get();
onChange && onChange(currenValue);
} catch (err) {}
},
[onChange]
);
// 初始化JSON编辑器
const initEditor = useCallback(() => {
if (!editorObj.current) {
const totalOptions = {
mode: 'code',
onChangeText: handleChange,
...options,
};
editorObj.current = new JSONEditor(editorRef.current, totalOptions);
}
}, [handleChange, options]);
useEffect(() => {
initEditor();
}, [initEditor]);
// 监听外部传入的value
useEffect(() => {
try {
if (value && !_.isEqual(editorObj.current.get(), value)) {
editorObj.current.update(value);
}
} catch (error) {
// 当编辑器内容为空时,editorObj.current.get()会抛出异常,所以这里需要捕获
}
}, [value]);
return <div className={styles['sm-json-editor']} ref={editorRef} />;
};
export default SMJsonEditor;
2、样式文件,(当然你的可以不用加:global(),普通写就可以了,我这里是项目原因要这样写)
.sm-json-editor {
width: 70%;
padding: 0;
// 这句是必要的,是要解决一个样式的Bug
:global(.ace-jsoneditor) {
font-size: 12px !important;
}
:global(.jsoneditor-menu) {
display: none;
}
:global(.jsoneditor-navigation-bar) {
display: none;
}
:global(.jsoneditor-outer.has-nav-bar.has-main-menu-bar) {
margin-top: 0;
padding-top: 0;
}
}
3.要使用这个组件直接引入就可以了