1、安装
npm install react-codemirror2 codemirror --save
2、使用
1 import {UnControlled as CodeMirror} from 'react-codemirror2' 2 import 'codemirror/lib/codemirror.js' 3 import 'codemirror/lib/codemirror.css'; 4 // 主题风格 5 import 'codemirror/theme/solarized.css'; 6 // 代码模式,clike是包含java,c++等模式的 7 import 'codemirror/mode/clike/clike'; 8 import 'codemirror/mode/css/css'; 9 //ctrl+空格代码提示补全 10 import 'codemirror/addon/hint/show-hint.css'; 11 import 'codemirror/addon/hint/show-hint'; 12 import 'codemirror/addon/hint/anyword-hint.js'; 13 //代码高亮 14 import 'codemirror/addon/selection/active-line'; 15 //折叠代码 16 import 'codemirror/addon/fold/foldgutter.css'; 17 import 'codemirror/addon/fold/foldcode.js'; 18 import 'codemirror/addon/fold/foldgutter.js'; 19 import 'codemirror/addon/fold/brace-fold.js'; 20 import 'codemirror/addon/fold/comment-fold.js'; 21 import 'codemirror/addon/edit/closebrackets'; 22 import 'codemirror/addon/edit/matchBrackets'; 23 24 export default class Index extends Component { 25 constructor() { 26 super(); 27 this.instance = null; 28 } 29 state = { 30 data:'', 31 } 32 render(){ 33 const {data}=this.state 34 let that=this 35 return( 36 <CodeMirror 37 editorDidMount={editor => { this.instance = editor }} 38 value={data} 39 options={{ 40 mode: {name:'text/css'}, 41 theme: 'solarized dark', 42 autofocus:true,//自动获取焦点 43 styleActiveLine:true,//光标代码高亮 44 lineNumbers: true, //显示行号 45 smartIndent:true, //自动缩进 46 //start-设置支持代码折叠 47 lineWrapping:true, 48 foldGutter:true, 49 gutters:['CodeMirror-linenumbers','CodeMirror-foldgutter'],//end 50 extraKeys:{ 51 "Ctrl":"autocomplete", 52 "Ctrl-S": function (editor) { 53 that.codeSave(editor) 54 }, 55 "Ctrl-Z":function (editor) { 56 editor.undo(); 57 },//undo 58 "F8":function (editor) { 59 editor.redo(); 60 },//Redo 61 }, 62 matchBrackets: true, //括号匹配,光标旁边的括号都高亮显示 63 autoCloseBrackets: true //键入时将自动关闭()[]{}''"" 64 }} 65 // onChange={this.codeOnChange} 66 67 // 在失去焦点的时候触发,这个时候放数据最好 68 // onBlur={this.codeOnBlur} 69 70 // // 这个必须加上,否则在一些情况下,第二次打开就会有问题 71 // // onBeforeChange={(editor, data, value) => { 72 // // console.log("onBeforeChange fresh") 73 // // console.log(JSON.stringify(data)); 74 // // }} 75 // /* HERE: pick out only the value. and might as well get name. */ 76 /> ) 77 }}