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

@monaco-editor/react中getContentHeight返回值异常问题咨询

@monaco-editor/react中getContentHeight返回值不符合预期,如何获取真实内容高度?

问题确认

你遇到的确实是@monaco-editor/react的已知问题,该库封装的getContentHeight()方法返回的是编辑器容器高度,而非实际内容高度,和方法描述的行为不符,相关问题已在项目仓库中被记录。

替代方案:直接使用原生Monaco API计算真实内容高度

可以跳过封装层,调用Monaco Editor原生API计算真实内容高度,核心逻辑是总行数 × 单行高度 + 内容区上下内边距:

修改后的代码示例

import * as React from 'react';
import MonacoEditor from '@monaco-editor/react';
import * as monaco from 'monaco-editor';

export default class EditorBasic extends React.Component<{}, {}> {
  editor: any;

  _handleEditorDidMount(editor, monacoInstance) {
    this.editor = editor;
    this.editor.onDidContentSizeChange(this.handleResize.bind(this));
  }

  updateHeight = () => {
    const model = this.editor.getModel();
    if (!model) return;
    
    // 获取单行高度配置
    const lineHeight = this.editor.getOption(monaco.editor.EditorOption.lineHeight);
    // 获取内容总行数
    const lineCount = model.getLineCount();
    // 获取内容区上下内边距
    const padding = this.editor.getOption(monaco.editor.EditorOption.padding);
    
    // 计算真实内容高度
    const actualContentHeight = lineHeight * lineCount + padding.top + padding.bottom;
    console.log('真实内容高度:', actualContentHeight);
  };

  handleResize() {
    this.editor && this.updateHeight();
  }

  render() {
    return (
      <MonacoEditor
        width="400px"
        height="500px"
        options={{ minimap: { enabled: false }, lineNumbers: 'off' }}
        defaultLanguage="javascript"
        defaultValue="content"
        onMount={this._handleEditorDidMount.bind(this)}
        theme="vs-dark"
      />
    );
  }
}

说明

  • 该方式依赖原生API获取编辑器配置与模型数据,计算结果能准确反映当前内容的实际高度
  • 若编辑器有自定义行高、内边距等配置,计算逻辑会自动适配

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:45:34