react代码编辑器 react-ace

首先说一下网上其他的编辑器:

轻量级:

1.codeMirror :文档和代码对不上,没有diff功能

github地址:https://github.com/codemirror/CodeMirror
示例代码:https://uiwjs.github.io/react-codemirror/

2.react-code-diff 最近一次维护2018年,直接报错无法使用

重量级:

1.monaco :微软出品,值得信赖

github地址:https://github.com/microsoft/monaco-editor

2.diff2html:也是功能很全的编辑器

官网:https://diff2html.xyz/
gitbub地址:https://github.com/rtfpessoa/diff2html

3.aceEditor:今天的重点

官网:https://ace.c9.io/#nav=about&api=editor
github地址:https://github.com/ajaxorg/ace

aceEditor其他版本

官方的aceEditor是js版的,后续有其他团队陆续出了vue版和react版,是官方的拓展版本,使用可参考官方的文档,其中字段名和方法名都和官方一致,方便使用。

vue版github地址:https://github.com/chairuosen/vue2-ace-editor
react版github地址:https://github.com/securingsincity/react-ace

react版aceEditor

安装

npm install react-ace ace-builds

使用方法:

import AceEditor from 'react-ace';
import 'ace-builds/src-noconflict/mode-jsx';// jsx模式的包
import 'ace-builds/src-noconflict/theme-monokai';// monokai的主题样式
import 'ace-builds/src-noconflict/ext-language_tools'; // 代码联想

const jsx = `import AceEditor from 'react-ace';
import 'ace-builds/src-noconflict/mode-golang'; // sql模式的包
import 'ace-builds/src-noconflict/mode-jsx';// mysql模式的包`;

<AceEditor
	mode='jsx'
    theme="monokai"
    name="app_code_editor"
    fontSize={14}
    showPrintMargin
    height="200px"
    width="1000px"
    showGutter
    onChange={value => {
         console.log(value); // 输出代码编辑器内值改变后的值
	}}
    value={jsx}
    wrapEnabled
    highlightActiveLine  //突出活动线
    enableSnippets  //启用代码段
    setOptions={{
    	enableBasicAutocompletion: true,   //启用基本自动完成功能
        enableLiveAutocompletion: true,   //启用实时自动完成功能 (比如:智能代码提示)
        enableSnippets: true,  //启用代码段
        showLineNumbers: true,
        tabSize: 2,
    }}
    annotations={[{ row: 0, column: 2, type: 'error', text: 'Some error.'}]} // 错误,警告
/>

效果

image

diff用法

import { diff as DiffEditor } from "react-ace";

const goLang = `package main
import "fmt"

func main() {
  fmt.Println("Hello, 世界")
}`;

const goLang1 = `package main
import "fmt"

func main() {
  fmt.Println("Hello, 世界");
  fmt.Println("Hello, 世界");
}`;

<DiffEditor
    mode='golang'
    theme="monokai"
    value={[goLang, `${goLang1};`]}
    height="1000px"
    width="1000px"
/>

image

注意:不定义样式看不见效果,className为:.codeMarker

.codeMarker {
    background: #fff677;
    position: absolute;
    z-index: 20;
}

posted @ 2022-10-11 15:24  Tommy_marc  阅读(1517)  评论(0编辑  收藏  举报