安装
npm install react-ace ace-builds
或者
yarn add react-ace ace-builds
在 React 组件中引入所需的包:
import {useEffect, useRef} from 'react';
import AceEditor from 'react-ace';
import 'ace-builds/src-noconflict/mode-sql'; // 引入 SQL 模式
import 'ace-builds/src-noconflict/theme-github'; // 引入 GitHub 主题
// 如果要有代码提示,下面这句话必须引入!!!
import 'ace-builds/src-noconflict/ext-language_tools'
const SqlEditor = (props: any) => {
const editorInstance = useRef<any>() // 获取编辑器实例
const {placeholder, defaultValue, onChange, completers, height} = props
const complete = (editor: any) => {
editor.completers = [
// 自己的代码提示
{
getCompletions: function (
editor: any,
session: any,
pos: any,
prefix: any,
callback: any
) {
callback(null, completers)
},
},
// 编辑器的代码提示
// ...editor.completers,
]
}
useEffect(() => {
// !动态改变编辑器的代码提示,必须重新设置
complete(editorInstance.current.editor)
}, [completers])
return (
<AceEditor
ref={editorInstance}
placeholder={placeholder}
mode="sql"
theme="github"
defaultValue={defaultValue}
name="UNIQUE_ID_OF_EDITOR"
fontSize={14}
editorProps={{$blockScrolling: true}}
onChange={onChange}
onPaste={onChange}
onLoad={complete}
showPrintMargin={false}
showGutter={true}
highlightActiveLine={true}
setOptions={{
useWorker: false,
enableBasicAutocompletion: true,
enableLiveAutocompletion: true,
enableSnippets: true,
showLineNumbers: true,
tabSize: 2,
}}
width="100%"
height={height ?? "80%"}
/>
);
};
export default SqlEditor;
页面引用
<AceEditor
defaultValue={sqlQuery}
completers={autocomplete ? completers : []}
onChange={(e: React.SetStateAction<string>) => setSqlQuery(e)}
placeholder="Please enter your sql"/>
其中completers是在输入的时候提示的文字数组,数据格式如下
const completers = [
{
meta: 'sql',
name: 'SELECT',
value: 'SELECT',
score: 100
},
{
meta: 'sql',
name: 'SET',
value: 'SET',
score: 100,
}
]
最终效果
参考来源 https://www.jianshu.com/p/cc9f5eb87aa2