在我的react应用程序中,给出editors
是一个由当前在应用程序中打开的用monaco.editor.create()
创建的所有编辑器组成的数组,假设我有以下内容:
const resizeObserver = useRef(new ResizeObserver(entries => {
console.log('entries = ', entries);
for(let entry of entries) {
console.log('target = ', entry.target);
const editor = getEditor(entry.target.id);
console.log('editor = ', editor);
editor.layout({} as monaco.editor.IDimension);
}
}));
它正确启动,但编辑器没有调整大小。但假设我只调整当前编辑器的大小:
window.onresize = () => {
const editor = editors[0];
editor.layout({} as monaco.editor.IDimension);
}
这个很好用。我遗漏了什么?
发布于 2022-06-23 06:58:38
在React应用程序中,当页面上只有一个可见编辑器时,只使用一个编辑器。当编辑器实例不可见时,不要将它们存储在操作的某处。相反,使用componentDidMount
在(仅)编辑器实例中加载一个新模型,并在componentUpdated
中保存编辑器的状态。下面是一个代码编辑器组件,它完成了所有这些工作。
对于调整大小的操作,请在编辑器组件中使用调整大小观察者。在它的建筑中设置它:
if (typeof ResizeObserver !== "undefined") {
this.resizeObserver = new ResizeObserver(this.handleEditorResize);
}
并处理编辑器组件中的大小调整,如下所示:
private handleEditorResize = (entries: readonly ResizeObserverEntry[]): void => {
if (entries.length > 0) {
const rect = entries[0].contentRect;
this.editor?.layout({ width: rect.width, height: rect.height });
}
};
在卸载组件时,不要忘记清理:
public componentWillUnmount(): void {
...
this.resizeObserver?.unobserve(this.hostRef.current as Element);
}
https://stackoverflow.com/questions/72704033
复制相似问题