react-ace 常用配置
1.引入
import AceEditor from "react-ace";
// 按需引入语言包
import "ace-builds/src-noconflict/mode-sql"; // sql模式的包
import "ace-builds/src-noconflict/mode-mysql"; // mysql模式的包
import "ace-builds/src-noconflict/mode-python"; // python模式的包
// 主题样式包
import "ace-builds/src-noconflict/theme-eclipse"; // eclipse的主题样式
import "ace-builds/src-noconflict/ext-language_tools";
2.简单使用
<AceEditor
// 配置编译器语言 sql,python,java等 https://github.com/thlorenz/brace/tree/master/mode
mode='mysql'
// 配置编译器主题色 多种配色 https://www.cnblogs.com/summer-qd/p/15305746.html
theme="eclipse"
// 为编译器命名,后续需要使用editor的方法时可以用到
name="editor1"
// 指定文字大小
fontSize={14}
// 默认情况下ace编辑器中会有一道竖线标识打印的边距,可以通过setShowPrintMargin来控制其是否显示
showPrintMargin={false}
showGutter
// 编译器value改变时触发
onChange={(value) => {
console.log(value); // 输出代码编辑器内值改变后的值
}}
// 编辑器内的值
value={sqlValue}
wrapEnabled
highlightActiveLine //突出活动线
enableSnippets //启用代码段
style={{ width: '100%', height: '100%' }}
setOptions={{
enableBasicAutocompletion: true, //启用基本自动完成功能
enableLiveAutocompletion: true, //启用实时自动完成功能 (比如:智能代码提示)
enableSnippets: true, //启用代码段
showLineNumbers: true,
tabSize: 2,
}}
/>
```
3.代码格式化
import * as Formatter from "sql-formatter";
<AceEditor value={Formatter.format(sqlValue)} />;
4.自定义代码提示
<AceEditor
// 编译器加载前
onLoad={complete}
/>
const complete = (editor) => {
editor.completers.push({
getCompletions: function (editors, session, pos, prefix, callback) {
callback(null, completers);
},
});
};
// 自定义代码提示
const completers = [
{
name: 'chen',
value: 'chen',
score: 100,
meta: 'keyword',
},
{
name: '${s}',
value: 'function',
score: 100,
meta: 'test',
},
];
```
5.插入代码段
// 失去焦点
<AceEditor
onBlur={(e, editor) => {
const cursor = editor.getCursorPosition();
// 定义失去焦点时的光标位置
setCursorPosition(cursor);
}}/>
// 插入代码段
// 可根据事件进行代码插入
const onClick=()=> {
const editor = edit('editor1');
// cursorPosition(获取的光标位置), insertSql(要插入的代码)
editor.session.insert(cursorPosition, insertSql);
};
```