需求:
- 需要做一个界面提供给客户做json 的编辑
- 但是客户可能不理解json 的格式规范
- 做一个可以编辑key value 的界面,然后自动格式化
进程:
- 找到对应的插件
- jsoneditor
npm install jsoneditor
- 参考: https://github.com/josdejong/jsoneditor/tree/master
-
import JSONEditor from 'jsoneditor'; import 'jsoneditor/dist/jsoneditor.css';
代码引用
-
jsoneditor 需要依存于div所以需要先指定一个div
<div style={{height: props.height}} className="jsoneditor-react-container" ref={containerRef} />
react 使用的是ref, 普通的js 可以使用 documemt.getById(), style 里的高,可以限制jsoneditor的高度,不然jsoneditor 就会基于json 的长度无限增长
-
const jsonEditor = new JSONEditor(containerRef.current, options, props.json)
创建对应的jsoneditor, 并导入到对应的div 中
-
options:参考https://github.com/josdejong/jsoneditor/blob/master/docs/api.md
-
常用的有mode (tree, text, code), enableSort(boolen), enableTransform(boolen), schema(object)
-
exsample: https://github.com/josdejong/jsoneditor/tree/master/examples
结果展示:
完整代码块:
import React, {useEffect, useRef} from 'react';
import JSONEditor from 'jsoneditor';
import 'jsoneditor/dist/jsoneditor.css';
export type JsonEditorProps = {
json: object;
height: number;
editJsonRef: (editJson) => object;
};
const JsonEditorBox: React.FC<JsonEditorProps> = (props) => {
const containerRef = useRef();
const editor = useRef();
const initJsonEditor = () => {
const options = {
enableSort: false,
enableTransform: false,
};
const jsonEditor = new JSONEditor(containerRef.current, options, props.json)
editor.current = jsonEditor;
props.editJsonRef(jsonEditor);
}
useEffect(() => {
initJsonEditor();
}, [])
useEffect(() => {
if (editor.current) {
editor.current.set(props.json);
}
}, [props.json])
return (
<div style={{height: props.height}} className="jsoneditor-react-container" ref={containerRef} />
)
}
export default JsonEditorBox
写在最后:
- 还有另一个插件,这边看起来也很有意思 josn-editor
- 插件地址:https://www.npmjs.com/package/json-editor
- demo:https://www.jeremydorn.com/json-editor
- 这是通过解析 json schema 来进行界面的渲染,可以很好的控制用户的操作范围,规范key 和value 的行为
- 当然上一个插件也有schema 的功能
- 预览这个插件