代码编辑组件
01. 说明
可用来高亮多种编程语言。
使用效果:

02. API
CodeMirror
| 参数 | 说明 | 类型 | 默认值 | 必输 | 
|---|---|---|---|---|
| value | 编辑器的初始值,可以是字符串或文档 | string | '' | 否 | 
| className | 编辑器的class样式 | string | hzero-codemirror | 否 | 
| fetchCodeMirror | 获取编辑器对象 | function(editor) | e => e | 否 | 
| onChange | 组件值变化的监听事件 | function(editor, data,value) | 否 | |
| onBeforeChange | 组件值变化前的监听事件 | function(editor, data, value, [next]) | 否 | |
| options | 用于配置组件其他属性,比如组件主题,详见下方描述 | object | {} | 否 | 
options 参数(部分)
| 参数 | 说明 | 类型 | 默认值 | 必输 | 
|---|---|---|---|---|
| theme | 编辑器主题风格 | string | ‘default’ | 否 | 
| className | 编辑器的class样式 | string | hzero-codemirror | 否 | 
| lineNumbers | 显示行号 | boolean | true | 否 | 
| mode | 以什么格式高亮代码 | string | yaml | 是 | 
| autoFocus | 自动获取焦点 | boolean | true | 否 | 
| readOnly | 是否只读,设置为 nocursor后将只读且不自动获取焦点 | boolean/string | false | 否 | 
| cursorHeight | 设置行高 | number | 0.85 | 否 | 
几种常用的mode:
- javascript: text/javascript
- json: application/json
- java: text/x-java
- xml: application/xml
- sql: text/x-sql
- yaml: yaml
更多mode设置请查看codemirror mode
PS: 在此只罗列出一部分常用的属性,更多配置项请查看codemirror config。
03. 使用示例
- 
- 引入CodeMirror组件。
 
- 引入
  import CodeMirror from 'components/CodeMirror';
如果使用的mode: 'text/x-java',java模式高亮代码,需要在引入组件前引入相应的样式文件:
  import 'codemirror/mode/clike/clike';
  import CodeMirror from 'components/CodeMirror';
ps: 不同模式的样式引入请查看codemirror mode。
- 
- 配置props。
 
- 配置
  const codeMirrorProps = {
    value: configYaml,
    options: {
      theme: 'default',
      mode: 'yaml',
    },
    onChange: this.handleCodeChange,
  };
- 
- 使用CodeMirror组件。
 
- 使用
  <CodeMirror
    codeMirrorProps={codeMirrorProps}
    fetchCodeMirror={editor => this.setCodeMirror(editor)}
  />
- 
- 获取编辑器对象
 
  // 定义全局的遍历存放editor对象,或者使用state存储
  codeMirrorEditor;
  @Bind
  setCodeMirror(editor) {
    this.codeMirrorEditor = editor;
  }
- 
- 获取value
 
- 获取
  const content = this.codeMirrorEditor.getValue();
如果在Form中使用,需要自行设置表单域的值:
- props属性配置
  const codeMirrorProps = {
    value: form.getFieldValue('templateContent'),
    onBeforeChange: this.codeChange,
  };
- 表单中使用
  <Form.Item
    label="html内容"
  >
    {getFieldDecorator('templateContent', {
      initialValue: templateContent,
    })(
      <Codemirror
        codeMirrorProps={codeMirrorProps}
      />
    )}
  </Form.Item>
- 使用onBeforeChange/onChange事件设置表单域值
  /**
   * 编辑代码后更新数据
   * @param {object} editor - 编辑器对象
   * @param {object} data - 数据对象
   * @param {string} value - 编辑后的代码
   */
  @Bind()
  codeChange(editor, data, value) {
    const { form } = this.props;
    form.setFieldsValue({ templateContent: value });
  }