react-ace编辑器-格式化JSON数据

本文介绍了如何在React应用中使用ace编辑器来格式化和验证JSON数据,包括安装、配置、基本使用及编辑器属性的设置。
部署运行你感兴趣的模型镜像

1、安装命令

// 安装 react-ace
yarn add react-ace  或者  npm install react-ace
// 安装 js-yaml
npm install js-yaml

2、导入ace 组件的相关配置信息

// 1、引入 react-ace
import AceEditor from “react-ace”;
// 2、ace mode 模式 json 格式
import “ace-builds/src-noconflict/mode-json”;
// 3、ace theme 主题 monokai
import “ace-builds/src-noconflict/theme-monokai”;
// 4、ace 语法:代码联想
import “ace-builds/src-noconflict/ext-language_tools”;
// 5、检测是否是json数据
const jsonlint = require(‘jsonlint-mod’)

// 6、其他引入项
import 'ace-builds/src-noconflict/mode-jsx';// jsx模式的包
import 'ace-builds/src-noconflict/mode-golang'; // 
// js编辑器插件中实现sql格式化 sql-formatter
import { format } from 'sql-formatter';
import 'ace-builds/src-noconflict/mode-sql'; // sql模式的包
import 'ace-builds/src-noconflict/mode-mysql';// mysql模式的包
import 'ace-builds/src-noconflict/theme-xcode';// xcode,(亮白)的主题样式
import "ace-builds/src-noconflict/theme-twilight";// twilight,(暗黑)的主题样式
//以下import的是风格,还有好多种,可以根据自己需求导入
// github、tomorrow、kuioir、twilight、xcode、textmeta、terminal、solarized-light、solarized-dark
import 'ace-builds/src-noconflict/ext-language_tools'; //(编译代码的文件)


// 转成YAML形式展示-需再引入以下几项。
import yaml from 'js-yaml';
// language_tools语言工具,(这个好像是检测语法,有点忘了,想不起来从哪里找到的)
import 'brace/ext/language_tools';
// searchbox过滤框,快捷键ctrl+F
import 'brace/ext/searchbox';
import 'brace/mode/yaml';
import 'brace/theme/monokai';

3,组件使用

<AceEditor
  mode="json"
  theme="monokai"
  value={ json字符串 }
  placeholder={“默认json数据”}
  onChange={ onChange }
  name="UNIQUE_ID_OF_DIV"
  highlightActiveLine={false}
  displayIndentGuides={false}
  editorProps={{ $blockScrolling: false }}
  style={{width: '100%', height: height }}
  setOptions={{
    enableBasicAutocompletion: true,
    enableLiveAutocompletion: true,
    enableSnippets: true,
    showLineNumbers: true,
    tabSize: 2,
  }}
/>

4、检测输入数据是否符合json数据格式规范

function debounce(fn, delay) {
  let timer = null;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...arguments), delay);
  };
}
const onChange = debounce(jsonlintStr, 2000);
// let onChange = value => {let yamlTempValue = value;};
const jsonlintStr = (val) => {
      if(val.length===0) return false
      try {
        let result = jsonlint.parse(val);
        if(result){
          // 验正成功  doing。。。
        }
      } catch(e) {
        message.warning(e.message);
      }
  }

5、基本使用汇总

import React from 'react'
import { message } from  "antd"
import AceEditor from "react-ace";
import "ace-builds/src-noconflict/mode-json";
import "ace-builds/src-noconflict/theme-monokai";
import "ace-builds/src-noconflict/ext-language_tools";

const jsonlint = require('jsonlint-mod')
function debounce(fn, delay) {
  let timer = null;
  return function () {
    clearTimeout(timer);
    timer = setTimeout(() => fn(...arguments), delay);
  };
}
const Index = (props) => {
  const placeholder =  (props.value && JSON.parse(props.value))
  const { height = 300 } = props
  const jsonlintStr = (val) => {
      if(val.length===0) return false
      try {
        let result = jsonlint.parse(val);
        if(result){
          props.onChange && props.onChange(val)
        }
      } catch(e) {
        message.warning(e.message);
      }
  }
  const onChange = debounce(jsonlintStr, 2000);
  return (
    <AceEditor
      mode="json"
      theme="monokai" // 设置主题 xcode cobalt monokai,twilight,(暗黑),xcode,(亮白)
      value={placeholder && JSON.stringify(placeholder,null,'\t') }
      // value={(content && yaml.dump(content)) || ''} // 取到YAML的字符串,换成YAML格式展示
      placeholder={"{\n   }"}
      onChange={onChange}
      // onChange={value => { console.log(value);}} // 输出代码编辑器内值改变后的值
      name="UNIQUE_ID_OF_DIV" // 唯一名
      highlightActiveLine={false}
      displayIndentGuides={false}
      editorProps={{ $blockScrolling: false }}
      style={{width: '100%', height: height }}
      setOptions={{
        enableBasicAutocompletion: true, //启用基本自动完成功能 不推荐使用
        enableLiveAutocompletion: true,//启用实时自动完成功能 (比如:智能代码提示)
        enableSnippets: true,//启用代码段
        showLineNumbers: true,
        tabSize: 2,
        wrap: true, // 换行
        autoScrollEditorIntoView: true, // 自动滚动编辑器视图
      }}
      annotations={[{ row: 0, column: 2, type: 'error', text: 'Some error.'}]} // 错误,警告
       onBlur:(event,e)=>{
        const value2 = e.getValue(); // 获取代码内容
        try {
            let json0 = jsonlint().parse(value2);//jsonlint自己找代码来判断当前错误行数是多少,
            let json1 = JSON.stringify(json0)
        }catch (e) {

        }
        if(e.getSession().getAnnotations().length !== 0){ // 判断代码格式是否有误
            message.error("必须输入 json 格式字符串!");
            return;
        }
      },
    />
  )
}

export default Index

6、编辑器属性

PropDefaultTypeDescription
name‘ace-editor’String用于编辑器的唯一ID
mode‘’String解析和代码突出显示的语言
splits2Number视图拆分
orientation‘beside’String拆分的方向在旁边还是在下面
theme‘’String使用的主题
value‘’Array of Strings设置值
defaultValue‘’Array of Strings每个编辑器的默认值
height‘500px’ ·String高度的CSS值
width‘500px’String宽度的CSS值
classNameString自定义类名
fontSize12Number字体大小的像素值
showGuttertrueBoolean显示槽
showPrintMargintrueBoolean显示打印边距
highlightActiveLinetrueBoolean突出显示活动行
focusfalseBoolean是否聚焦
cursorStart1Number光标的位置
wrapEnabledfalseBoolean包装线
readOnlyfalseBoolean使编辑器为只读
minLinesNumber显示的最小行数
maxLinesNumber显示的最大行数
enableBasicAutocompletionfalseBoolean启用基本自动补全
enableLiveAutocompletionfalseBoolean启用实时自动补全
enableSnippetsfalseBoolean启用摘要
tabSize4Numbertab空格值
debounceChangePeriodnullNumberonChange事件的抖动延迟时间
onLoadFunction在编辑器加载时调用。第一个参数是编辑器的实例
onBeforeLoadFunction在编辑器加载之前调用。第一个参数是的实例ace
onChangeFunction发生在文档更改上,它具有2个参数,每个编辑器的值和事件
onCopyFunction由编辑器copy事件触发,并将文本作为参数传递
onPasteFunction由编辑器paste事件触发,并将文本作为参数传递
onSelectionChangeFunction由编辑器selectionChange事件触发,并且将Selection作为第一个参数传递,并将事件作为第二个参数传递
onCursorChangeFunction由编辑器changeCursor事件触发,并且将Selection作为第一个参数传递,并将事件作为第二个参数传递
onFocusFunction由编辑器focus事件触发
onBlurFunction由编辑器blur事件触发
onInputFunction由编辑器input事件触发
onScrollFunction由编辑器scroll事件触发
editorPropsObject可直接应用于Ace编辑器实例的属性
setOptionsObject直接应用于Ace编辑器实例的选项
keyboardHandlerString对应于要设置的绑定模式(例如vim或emacs)
commandsArray新命令添加到编辑器
annotationsArray of Arrays要在编辑器中[{ row: 0, column: 2, type: ‘error’, text: ‘Some error.’}]显示的注释,即在装订线中显示
markersArray of Arrays要在编辑器中显示的标记,即[{ startRow: 0, startCol: 2, endRow: 1, endCol: 20, className: ‘error-marker’, type: ‘background’ }]
styleObject驼峰属性

您可能感兴趣的与本文相关的镜像

ACE-Step

ACE-Step

音乐合成
ACE-Step

ACE-Step是由中国团队阶跃星辰(StepFun)与ACE Studio联手打造的开源音乐生成模型。 它拥有3.5B参数量,支持快速高质量生成、强可控性和易于拓展的特点。 最厉害的是,它可以生成多种语言的歌曲,包括但不限于中文、英文、日文等19种语言

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值