【问题标题】:How to change monaco editor background colour in React如何在 React 中更改 monaco 编辑器背景颜色
【发布时间】:2020-04-29 21:25:21
【问题描述】:

我正在寻找更改 monaco 编辑器的背景颜色。我在 React 中使用以下 monaco npm 包:Monaco React

有没有办法在下面的编辑器组件中做到这一点?我在下面的选项对象完美地工作,所以希望对编辑器背景颜色做类似的事情。

我应该为此使用defineTheme function 吗?

这是我正在尝试使用的编辑器代码:

<Editor
        height="90vh"
        width="870px"
        language="javascript"
        line="2"
        options={{
          minimap: {
            enabled: false,
          },
          fontSize: 18,
          cursorStyle: "block",
          wordWrap: "on",
        }}
        defineTheme={{
          themeName: "my-theme",
          themeData: {
            colors: {
              "editor.background": "#000000",
            },
          },
        }}
        value={"// write your code here"}
        editorDidMount={handleEditorDidMount}
      />

【问题讨论】:

  • 根据props docs 看来theme 只需要light|dark 的枚举字符串。

标签: reactjs monaco-editor


【解决方案1】:

不幸的是,文档对此不是很清楚,但您不能在定义后简单地将自定义主题添加到 &lt;Editor /&gt; 组件本身。
您需要从 Monaco 实例调用两个不同的函数。 第一个是monaco.editor.defineTheme(),在handleEditorDidMount。第二个是monaco.editor.setTheme() in handleEditorDidMount

似乎由于阶段的顺序,handleEditorDidMount 将在 Editor 组件与其他 props 一起渲染之后被调用,并且如果 theme 已被设置为一个 props,则它将被调用。 因此,要添加自定义主题,您可以省略 theme 属性,而是在 handleEditorDidMount 中添加 defineTheme('myTheme', {})setTheme('myTheme')

【讨论】:

    【解决方案2】:

    有两个步骤可以实现您的目标

    1. 使用自定义颜色定义您的自定义主题
    2. 通知摩纳哥使用该主题

    工作示例

    https://microsoft.github.io/monaco-editor/playground.html#customizing-the-appearence-exposed-colors

    如果你想在 React 中做, 在 ComponentDidMount (classComponent) 或 useEffect(functionalComponent) 中,使用 monaco 编辑器的 define theme 接口定义您的自定义主题。

    monaco.editor.defineTheme('my-theme', {
          base: 'vs',
          inherit: true,
          rules: [],
          colors: {
            'editor.background': '#000000',
          },
    });
    

    然后在渲染编辑器组件时将“我的主题”作为主题道具传递给编辑器组件。

    <Editor
       height="90vh"
       width="870px"
       language="javascript"
       theme="my-theme"
       line="2"
       options={{
         minimap: {
           enabled: false,
         },
         fontSize: 18,
         cursorStyle: "block",
         wordWrap: "on",
       }}
       value={"// write your code here"}
       editorDidMount={handleEditorDidMount}
    />
    

    在您使用的 npm 存储库中,有一个预定义的附加主题可用。 (night-dark)。 其定义如下

    {
        base: 'vs-dark',
        inherit: true,
        rules: [],
        colors: {
          'editor.background': '#202124',
        },
    },
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-22
      • 2020-06-12
      • 2014-07-31
      • 2016-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多