【问题标题】:how to make react-monaco-edtor responsive?如何使 react-monaco-editor 响应式?
【发布时间】:2020-08-24 17:54:09
【问题描述】:

我正在使用 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 覆盖组件 className。但是好像效果不太好。

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

您能帮我设计 CSS 以使其具有响应性吗?

【问题讨论】:

  • monaco-react 似乎与 Create-React-App 一起工作得更好。默认是响应式的

标签: html css reactjs monaco-editor


【解决方案1】:

只需在options设置automaticLayout: true

【讨论】:

    【解决方案2】:

    您可以添加一个调整大小处理程序,以便确定编辑器容器的可用空间并将其立即传递给您的 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);
    
    

    【讨论】:

    • 现在也试过了。仍然没有让它响应
    【解决方案3】:

    在 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 事件就可以了。

    【讨论】:

    • 注意:这只是部分解决方案。它仅在调整窗口大小时起作用。但是,如果编辑器嵌入在可调整大小的元素中并且已调整大小,则编辑器将无法正确更新。查看ResizeObserver 以获得更好的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-20
    • 2021-08-22
    • 1970-01-01
    相关资源
    最近更新 更多