基础使用
import React, { useState, useCallback, useRef } from "react";
import MonacoEditor from "react-monaco-editor";
import * as monaco from "monaco-editor";
const Demo = () => {
const [value, setValue] = useState("");
const editorRef = useRef<monaco.editor.IStandaloneCodeEditor>(); // 编辑器实例
const monacoRef = useRef<typeof monaco>(); // monaco 实例
// 获取编辑器实例
const editorDidMountHandle = useCallback(
(editor: monaco.editor.IStandaloneCodeEditor, monacoIns: typeof monaco) => {
editorRef.current = editor;
monacoRef.current = monacoIns;
},[]);
return (
<MonacoEditor
language="javascript"
height="100%"
theme="vs"
value={value}
onChange={setValue}
options={{
roundedSelection: false,
cursorStyle: "line",
wordWrap: "on",
}}
editorDidMount={editorDidMountHandle}
/>
);
};
editorInstance
和 monacoInstance
的区别:
editorInstance
:主要作用于编辑器上操作的方法,例如编辑器写入操作等。monacoInstance
:主要是编辑器语言相关的内容,例如变量提示、鼠标悬浮提示等。