React中使用jsoneditor

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.要使用这个组件直接引入就可以了

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值