You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Monaco编辑器点击添加代码仅首次生效问题及实现需求

解决Monaco编辑器点击按钮无法重置内容的问题

问题根源

  1. 手动编辑编辑器内容后,addCode状态未同步更新,再次点击按钮时设置的内容与当前addCode值一致,导致组件不触发重渲染,编辑器无响应。
  2. handleEditorDidMount中错误地将编辑器实例存入input状态,这是冗余操作,只需用editorRef保存实例即可。

方案一:受控模式(推荐)

通过onChange事件同步编辑器内容到addCode状态,确保状态与视图一致,每次点击按钮时强制更新内容:

import { useState, useRef } from "react";
import Editor from "@monaco-editor/react";

export default function IndexPage() {
  const [addCode, setAddCode] = useState("# code goes here");
  const editorRef = useRef(null);

  function handleEditorDidMount(editor) {
    editorRef.current = editor;
  }

  // 同步编辑器内容到React状态
  const handleEditorChange = (value) => {
    setAddCode(value);
  };

  const handleAddCode = () => {
    // 设置新内容,状态更新后编辑器自动同步
    setAddCode("print('Hello World!')");
  };

  return (
    <div>
      <div className="code-editor">
        <Editor
          width="100vh"
          height="40vh"
          theme="vs-dark"
          fontSize="14"
          defaultLanguage="python"
          defaultValue=""
          value={addCode}
          onMount={handleEditorDidMount}
          onChange={handleEditorChange}
        />
      </div>
      <br />
      <button onClick={handleAddCode}>Add code</button>
    </div>
  );
}

方案二:直接操作编辑器实例

利用保存的编辑器实例,点击按钮时直接调用setValue方法重置内容,无需依赖状态变化:

import { useState, useRef } from "react";
import Editor from "@monaco-editor/react";

export default function IndexPage() {
  const [addCode, setAddCode] = useState("# code goes here");
  const editorRef = useRef(null);

  function handleEditorDidMount(editor) {
    editorRef.current = editor;
    editor.setValue(addCode);
  }

  const handleAddCode = () => {
    const newCode = "print('Hello World!')";
    setAddCode(newCode);
    // 直接操作编辑器实例设置内容
    if (editorRef.current) {
      editorRef.current.setValue(newCode);
    }
  };

  return (
    <div>
      <div className="code-editor">
        <Editor
          width="100vh"
          height="40vh"
          theme="vs-dark"
          fontSize="14"
          defaultLanguage="python"
          defaultValue=""
          onMount={handleEditorDidMount}
        />
      </div>
      <br />
      <button onClick={handleAddCode}>Add code</button>
    </div>
  );
}

方案说明

  • 方案一遵循React受控组件逻辑,状态与视图完全同步,适合需要对编辑器内容做额外处理的场景。
  • 方案二更简洁直接,通过编辑器实例操作内容,适合仅需重置内容的简单场景。

内容的提问来源于stack exchange,提问作者StackUnderFlow

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 11:55:26