UNPKG

hc-code-mirror

Version:

code mirror

96 lines (85 loc) 2.73 kB
/** @format */ import { Controlled as CodeMirror } from 'react-codemirror2'; import React, { Component } from 'react'; import { get } from 'lodash'; import 'codemirror/mode/xml/xml.js'; import 'codemirror/mode/yaml/yaml.js'; import 'codemirror/mode/javascript/javascript.js'; import 'codemirror/mode/sql/sql.js'; import 'codemirror/mode/markdown/markdown'; import 'codemirror/addon/edit/matchbrackets.js'; import 'codemirror/addon/edit/closebrackets.js'; import 'codemirror/addon/fold/foldcode.js'; import 'codemirror/addon/fold/foldgutter.js'; import 'codemirror/addon/fold/brace-fold.js'; import 'codemirror/addon/fold/indent-fold.js'; import 'codemirror/addon/fold/comment-fold.js'; import 'codemirror/addon/lint/lint'; import 'codemirror/addon/lint/yaml-lint'; import './codemirror.less'; import './material.less'; import './neat.less'; const options = { mode: 'javascript', theme: 'material', lineNumbers: true, smartIndent: true, //智能缩进 indentUnit: 2, // 智能缩进单位为4个空格长度 indentWithTabs: true, // 使用制表符进行智能缩进 lineWrapping: true, // // 在行槽中添加行号显示器、折叠器、语法检测器` gutters: ['CodeMirror-linenumbers', 'CodeMirror-foldgutter', 'CodeMirror-lint-markers'], foldGutter: true, // 启用行槽中的代码折叠 autofocus: true, //自动聚焦 matchBrackets: true, // 匹配结束符号,比如"]、}" autoCloseBrackets: true, // 自动闭合符号 styleActiveLine: true // 显示选中行的样式 }; class MyCodeMirror extends Component { constructor(props) { super(props); this.state = { value: '' }; this.codeMirror = React.createRef(); } componentDidMount() { this.setState({ value: this.props.value }); } componentWillReceiveProps(nextProps) { this.setState({ value: nextProps.value || '' }); // setTimeout(() => { // this.codeMirror&&this.codeMirror.editor.refresh() // },100) } onChange = value => { get(this.props, 'onChange', () => { })(value); }; render() { return ( <div style={this.props.style} className={`custom-codemirror ${this.props.className}`}> <CodeMirror ref={this.codeMirror} value={this.state.value} options={Object.assign(options, this.props.options)} onBeforeChange={(editor, data, value) => { this.onChange(value); }} /> </div> ); } } export default MyCodeMirror; // default props MyCodeMirror.defaultProps = { style: {}, className: '', value: '', options: {}, onChange: value => { } };