如何让Monaco Editor的诊断窗口超出Allotment拆分面板?
问题描述
我使用Allotment实现了可拖拽拆分面板,在其中一个面板嵌入了Monaco Editor。鼠标悬停编辑器时会显示诊断窗口,但即使在style.css中设置.monaco-hover { z-index: 1000 !important },该窗口仍无法超出第一个面板。
解决方法
这个问题的核心原因是Allotment的面板(Pane)默认设置了overflow: hidden,会直接裁剪内部超出边界的元素,单纯调整z-index无法解决裁剪问题。需要从以下两方面修改:
- 取消面板的溢出裁剪
给包含Monaco Editor的面板添加自定义类名,然后修改其overflow属性,允许内容溢出显示:
- 修改组件代码中的面板定义:
<Allotment.Pane className="editor-pane"> <Editor {...你的编辑器配置} /> </Allotment.Pane>
- 在
style.css中添加样式:
.editor-pane { overflow: visible !important; } /* 同步修改Allotment内部容器的溢出限制 */ .allotment__panel.editor-pane { overflow: visible; }
- 确保悬浮窗口的层级与定位
调整Monaco悬浮窗口的定位和层级,避免被其他元素遮挡:
.monaco-hover { z-index: 9999 !important; position: fixed !important; /* 脱离面板的相对定位上下文 */ }
完整修改后的关键代码片段
App.js
import React from "react"; import { Allotment } from "allotment"; import "allotment/dist/style.css"; import "./style.css"; import Editor, { monaco } from "@monaco-editor/react"; monaco .init() .then((monaco) => { monaco.languages.registerHoverProvider("html", { provideHover: function (model, position) { console.log(position); return { range: new monaco.Range( 1, 1, model.getLineCount(), model.getLineMaxColumn(model.getLineCount()) ), contents: [ { value: "**SOURCE**" }, { value: "hey man, how are you?" } ] }; } }); }) .catch((error) => console.error("An error occurred during initialization of Monaco: ", error) ); export default class App extends React.Component { constructor(props) { super(props); this.state = { toExpand: true }; this.myRef = React.createRef(); } handleChange = (sizes) => { if (sizes.length > 1) { if (sizes[1] < 31) { this.setState({ toExpand: true }); } else { this.setState({ toExpand: false }); } } }; render() { return ( <div style={{ minWidth: 200, height: "100vh", overflowX: "auto", width: "auto", margin: "0" }} > <Allotment vertical onChange={this.handleChange} ref={this.myRef}> {/* 添加自定义类名editor-pane */} <Allotment.Pane className="editor-pane"> <Editor height="30vh" language="html" value={` <section> <div> <span> {{ some_value }} </span> </div> </section> `} options={{ selectOnLineNumber: true, lineNumbersMinChars: 0, glyphMargin: true, readOnly: true, hover: { enabled: true } }} /> </Allotment.Pane> <Allotment.Pane preferredSize="0%" minSize={20}> short <br /> short <br /> short <br /> short <br /> short <br /> short <br /> short <br /> short <br /> short <br /> short <br /> short <br /> short <br /> </Allotment.Pane> </Allotment> </div> ); } }
style.css
.editor-pane { overflow: visible !important; } .allotment__panel.editor-pane { overflow: visible; } .monaco-hover { z-index: 9999 !important; position: fixed !important; }
内容的提问来源于stack exchange,提问作者SoftTimur
相关产品推荐
相关产品推荐

