codemirror2 在antd的form中會出現(xiàn)無法錄入或者錄入報錯的問題,解決方法請查閱:
codemirrorwrapper - CodeSandbox
1. 安裝依賴
yarn add codemirror
yarn add react-codemirror2
2. 引入
// js
import Cm from "./extendCodeMirror.js"; // 代碼在文章底部, 用于初始化編輯器的格式化代碼的功能
import {UnControlled as CodeMirror} from 'react-codemirror2';
import 'codemirror/addon/fold/foldcode.js'; // 代碼折疊
import 'codemirror/addon/fold/foldgutter.js'; // 代碼折疊
import 'codemirror/addon/fold/brace-fold.js'; // 代碼折疊
import 'codemirror/addon/fold/comment-fold.js'; // 代碼折疊
import 'codemirror/addon/hint/javascript-hint.js'; // 自動提示
import 'codemirror/addon/hint/show-hint.js'; // 自動提示
import 'codemirror/addon/lint/lint.js'; // 錯誤校驗
import 'codemirror/addon/lint/javascript-lint.js'; // js錯誤校驗
import 'codemirror/addon/selection/active-line.js'; // 當(dāng)前行高亮
import 'codemirror/lib/codemirror.js'
import 'codemirror/mode/javascript/javascript.js'
// css
import 'codemirror/addon/fold/foldgutter.css'; // 代碼折疊
import 'codemirror/addon/hint/show-hint.css'; // 自動提示
import 'codemirror/addon/lint/lint.css' // 代碼錯誤提示
import 'codemirror/lib/codemirror.css' // 編輯器樣式
import 'codemirror/theme/idea.css' // 主題: idea
import 'codemirror/theme/solarized.css'
//聲明JSHINT
const jshint = require('../../../libs/codeMirror/jshint'); // jshit.js 在文章底部
window.JSHINT = jshint.JSHINT;
3.使用
<CodeMirror
editorDidMount={this.onEditorDidMount}
value={''}
options={{
extraKeys: { //配置按鍵
"Alt": "autocomplete", // 按下`alt`時出現(xiàn)代碼提示
},
lineNumbers: true, // 顯示行號
lineWrapping: false, // 自動換行
styleActiveLine: true, // 選中行高亮
mode: "javascript",
theme: "idea", // 主題配置
matchBrackets: true, // 匹配括號
hintOptions: {hint: this.synonyms}, // 自動提示配置
gutters: ["CodeMirror-lint-markers"],
lint: true, // 代碼出錯提醒
indentUnit: 4, // 縮進(jìn)配置(默認(rèn)為2)
}}
/>
// js
onEditorDidMount = editor => {
this.editor = editor;
editor.setSize("width", 'height'); // 設(shè)置編輯器寬高
// 綁定其他快捷鍵, 這里以按下ctrl-1 格式化編輯器代碼做示例
editor.addKeyMap({
'Ctrl-1': this.autoFormatSelection,
})
}
synonyms = (cm, option) => {
let comp = [
"要提示的代碼1",
"要提示的代碼2",
"..."
]
return new Promise(function (accept) {
setTimeout(function () {
var cursor = cm.getCursor(), line = cm.getLine(cursor.line);
var start = cursor.ch, end = cursor.ch;
while (start && /[a-zA-Z0-9_.]/.test(line.charAt(start - 1))) --start;
while (end < line.length && /[a-zA-Z0-9_.]/.test(line.charAt(end))) ++end;
var word = line.slice(start, end);
var result_comp = [];
for (let i = 0; i < comp.length; i++) {
if (comp[i].indexOf(word) !== -1) {
result_comp.push(comp[i]);
}
}
if (result_comp.length) {
return accept({
list: result_comp,
from: Cm.Pos(cursor.line, start),
to: Cm.Pos(cursor.line, end)
});
} else {
return accept(null)
}
}, 50)
})
}
autoFormatSelection = () => {
const script_length = this.editor.getValue().length;
const startPos = {line: 0, ch: 0, sticky: null};
const endPos = this.editor.doc.posFromIndex(script_length);
this.editor.setSelection(startPos, endPos);
this.editor.autoFormatRange(startPos, endPos);
this.editor.commentRange(false, startPos, endPos);
};
4.補(bǔ)充代碼
// extendCodeMirror.js
/* eslint-disable */
import * as CodeMirror from 'codemirror';
CodeMirror.extendMode("css", {
commentStart: "/*",
commentEnd: "*/",
newlineAfterToken: function(type, content) {
return /^[;{}]$/.test(content);
}
});
CodeMirror.extendMode("javascript", {
commentStart: "/*",
commentEnd: "*/",
// FIXME semicolons inside of for
newlineAfterToken: function(type, content, textAfter, state) {
if (this.jsonMode) {
return /^[\[,{]$/.test(content) || /^}/.test(textAfter);
} else {
if (content == ";" && state.lexical && state.lexical.type == ")") return false;
return /^[;{}]$/.test(content) && !/^;/.test(textAfter);
}
}
});
CodeMirror.extendMode("xml", {
commentStart: "<!--",
commentEnd: "-->",
newlineAfterToken: function(type, content, textAfter) {
return type == "tag" && />$/.test(content) || /^</.test(textAfter);
}
});
// Comment/uncomment the specified range
CodeMirror.defineExtension("commentRange", function (isComment, from, to) {
var cm = this, curMode = CodeMirror.innerMode(cm.getMode(), cm.getTokenAt(from).state).mode;
cm.operation(function() {
if (isComment) { // Comment range
cm.replaceRange(curMode.commentEnd, to);
cm.replaceRange(curMode.commentStart, from);
if (from.line == to.line && from.ch == to.ch) // An empty comment inserted - put cursor inside
cm.setCursor(from.line, from.ch + curMode.commentStart.length);
} else { // Uncomment range
var selText = cm.getRange(from, to);
var startIndex = selText.indexOf(curMode.commentStart);
var endIndex = selText.lastIndexOf(curMode.commentEnd);
if (startIndex > -1 && endIndex > -1 && endIndex > startIndex) {
// Take string till comment start
selText = selText.substr(0, startIndex)
// From comment start till comment end
+ selText.substring(startIndex + curMode.commentStart.length, endIndex)
// From comment end till string end
+ selText.substr(endIndex + curMode.commentEnd.length);
}
cm.replaceRange(selText, from, to);
}
});
});
// Applies automatic mode-aware indentation to the specified range
CodeMirror.defineExtension("autoIndentRange", function (from, to) {
var cmInstance = this;
this.operation(function () {
for (var i = from.line; i <= to.line; i++) {
cmInstance.indentLine(i, "smart");
}
});
});
// Applies automatic formatting to the specified range
CodeMirror.defineExtension("autoFormatRange", function (from, to) {
var cm = this;
var outer = cm.getMode(), text = cm.getRange(from, to).split("\n");
var state = CodeMirror.copyState(outer, cm.getTokenAt(from).state);
var tabSize = cm.getOption("tabSize");
var out = "", lines = 0, atSol = from.ch == 0;
function newline() {
out += "\n";
atSol = true;
++lines;
}
for (var i = 0; i < text.length; ++i) {
var stream = new CodeMirror.StringStream(text[i], tabSize);
while (!stream.eol()) {
var inner = CodeMirror.innerMode(outer, state);
var style = outer.token(stream, state), cur = stream.current();
stream.start = stream.pos;
if (!atSol || /\S/.test(cur)) {
out += cur;
atSol = false;
}
if (!atSol && inner.mode.newlineAfterToken &&
inner.mode.newlineAfterToken(style, cur, stream.string.slice(stream.pos) || text[i+1] || "", inner.state))
newline();
}
if (!stream.pos && outer.blankLine) outer.blankLine(state);
if (!atSol) newline();
}
cm.operation(function () {
cm.replaceRange(out, from, to);
for (var cur = from.line + 1, end = from.line + lines; cur <= end; ++cur)
cm.indentLine(cur, "smart");
cm.setSelection(from, cm.getCursor(false));
});
});
// console.log("初始化CodeMirror完成");
export default CodeMirror;
// jshint.js
//鏈接: https://pan.baidu.com/s/1mdTArljNyDybKOqKIL2XQQ 提取碼: d2b2 復(fù)制這段內(nèi)容后打開百度網(wǎng)盤手機(jī)App皇忿,操作更方便哦