json 格式化编辑

需求:

  • 需要做一个界面提供给客户做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

写在最后:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值