简体   繁体   English

如何使用 react-codemirror2 使用自定义 CodeMirror 模式

[英]How to use custom CodeMirror modes using react-codemirror2

How do you use custom CodeMirror modes when using react-codemirror2 ?使用react-codemirror2时如何使用自定义CodeMirror模式? Both CodeMirror.defineSimpleMode and CodeMirror.defineMode are undefined after I import as follows:我导入后CodeMirror.defineSimpleModeCodeMirror.defineMode都未定义,如下所示:

import {UnControlled as CodeMirror} from "react-codemirror2";
import 'codemirror/lib/codemirror.css';

Context: In my react project I'd like to use CodeMirror and define my own input language which matches against some regex's and then highlights them to indicate the user has entered them correctly.上下文:在我的反应项目中,我想使用CodeMirror并定义我自己的输入语言,该语言与某些正则表达式匹配,然后突出显示它们以指示用户已正确输入它们。 I also want line numbers, no wrapping, monospace fonts, therefore a code editor seems close to what I want to achieve.我还想要行号,没有换行,等宽 fonts,因此代码编辑器似乎接近我想要实现的目标。

You have two options to use custom modes using react-codemirror2.您有两个选项可以使用 react-codemirror2 使用自定义模式。

  1. Use the defineMode prop and pass in the mode and its function:使用defineMode并传入模式及其 function:
import { UnControlled as CodeMirror } from "react-codemirror2";
import 'codemirror/lib/codemirror.css';

<CodeMirror
  options={{
    lineNumbers: true,
    defineMode: {
      name: 'yourMode',
      fn: yourModeFunction
    },
    ...

  }}
  ...
/>;
  1. Separately import CodeMirror and define your mode before the control is rendered:在渲染控件之前单独导入 CodeMirror 并定义您的模式:
import { UnControlled as CodeMirrorControl } from "react-codemirror2";
import 'codemirror/lib/codemirror.css';
import CodeMirror from 'codemirror';

CodeMirror.defineMode('yourMode', yourModeFunction);

<CodeMirrorControl
  options={{
    lineNumbers: true,
    ...
    mode: 'yourMode',
  }}
  ...
/>;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM