如何使 react-monaco-editor 响应?

how to make react-monaco-edtor responsive?

我正在使用 react-monaco-editor 但我无法使其响应。它在组件中采用固定的高度和宽度。如果我改变屏幕尺寸,宽度保持不变。

    <MonacoEditor
      width="1200"
      height="600"
      language="typescript"
      theme="vs-dark"
      defaultValue="//type your code here"
      value={code}
      options={options}
      onChange={this.onChange}
      editorDidMount={this.editorDidMount}
      className='editor1'
    />

如果我从组件中删除宽度和高度,组件就会缩小。我尝试用 flex 覆盖组件类名。但是好像不太好用

.react-monaco-editor-container {
   flex: 2;
}

你能帮我 CSS 让它响应吗?

您可以添加一个调整大小处理程序,以便为您的编辑器容器找出可用的 space 并立即将其传递给您的 Monaco 编辑器。

还有不同的库可以帮助您: https://www.npmjs.com/package/react-resize-detector

在这里您可以找到一个使用上述库的沙盒示例: https://codesandbox.io/s/vibrant-goldwasser-3d8j7?fontsize=14&hidenavigation=1&theme=dark

import React from "react";
import { withResizeDetector } from "react-resize-detector";

const Editor = ({ width, height }) => (
  <div
    style={{
      background: "grey",
      height: height,
      width: width
    }}
  >
    Editor container with {width} x {height}
  </div>
);

export default withResizeDetector(Editor);

在一些事情对 CSS 不起作用之后,我尝试 javascript 来解决这个问题

  updateDimensions = () => {
    this.setState({
      width: window.innerWidth - 501,
      height: window.innerHeight - 50,
    });
  };

  componentDidMount() {
    window.addEventListener("resize", this.updateDimensions);
  }
  componentWillUnmount() {
    window.removeEventListener("resize", this.updateDimensions);
  }

heightwidth 存储在状态中并在 resize 事件上更改就完成了工作。

只需在options中设置automaticLayout: true