uiwjs / react-monacoeditor

Monaco Editor component for React.
https://uiwjs.github.io/react-monacoeditor/
MIT License
290 stars 24 forks source link

如何自动格式化代码 #160

Open UvDream opened 2 years ago

UvDream commented 2 years ago

求教,这个编辑器如何在初始化的时候格式化代码,而且我发现我这个右键格式化好像也不行是咋肥事,json格式的

image

我初始化格式代码是这样的

 editorDidMount={(editor) => {

                editor.getAction('editor.action.formatDocument').run();
              }}

发现没用

jaywcjlove commented 2 years ago
/**
 * an event emitted when the editor has been mounted (similar to `componentDidMount` of React)
 */
editorDidMount?: (editor: monaco.editor.IStandaloneCodeEditor, monaco: IMonacoEditor) => void;

getAction 方法存在?

@UvDream

UvDream commented 2 years ago

不存在,我看官方的那个这样格式化的,后来发现不存在,哈哈

jaywcjlove commented 2 years ago

@UvDream 应该是用 monaco 这个回调参数的吧

NIBUSHIYIGEREN commented 2 years ago

同问 该怎么格式化代码呢

jaywcjlove commented 2 years ago

@zhoujiaxu2014 https://github.com/microsoft/monaco-editor/issues/2664#issuecomment-922093401

<MonacoEditor
  language="json"
  value={`{"scope":"/build","moduleGenTarget":"commonjs"}`}
  editorDidMount={(editor, monaco) => {
    // 不起作用,这可能需要通过 ref 获取到 editor 对象执行 格式化
+    editor.getAction('editor.action.formatDocument').run();
  }}
  options={{
+    "formatOnPaste": true,
+    "formatOnType": true
  }}
/>  

@UvDream @zhoujiaxu2014

dc-orz commented 1 year ago
const monaco = useMonaco();
  useEffect(() => {
    if (monaco) {
      monaco.editor.addCommand({
        id: 'editor.action.formatDocument',
        run: () => undefined,
      });
    }
  }, [monaco]);

It works with React 18.0

xiaopujun commented 12 months ago
const monaco = useMonaco();
  useEffect(() => {
    if (monaco) {
      monaco.editor.addCommand({
        id: 'editor.action.formatDocument',
        run: () => undefined,
      });
    }
  }, [monaco]);

It works with React 18.0

This is great. It solves my problem perfectly.