monaco-editor
monaco-editor 大有来头,微软的 vs code 就脱胎于它。和 codemirror 类似,用于实现在线编辑器功能。
两者的具体对比参见文章 代码编辑器对比,这里主要讲一下 react-monaco-editor 的使用。
react-monaco-editor
react-monaco-editor 是对 monaco-editor 的封装,大部分 api 继承自 monaco-editor。 以下是 react-monaco-editor官方文档 给的使用示例:
import MonacoEditor from 'react-monaco-editor';
import React from 'react';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
code: '// 初始代码',
}
}
editorDidMount(editor, monaco) {
console.log('editorDidMount', editor);
editor.focus();
}
onChange(newValue, e) {
console.log('onChange', newValue, e);
}
render() {
const code = this.state.code;
const options = {
selectOnLineNumbers: true
};
return (
<MonacoEditor
width="800"
height="600"
language="javascript"
theme="vs-dark"
value={code}
options={options}
onChange={::this.onChange}
editorDidMount={::this.editorDidMount}
/>
);
}
}
除此之外的绝大多数属性,都在 options 属性里配置。react-monaco-editor 文档也很实在,直接链接到 Monaco Editor API, 如图 :
options
注意,这些属性都是 options 的子属性。我一开始就是直接传给 MonacoEditor 类,没有生效,仔细看文档才发现传错了。
代码示例:
<MonacoEditor
width="800"
height="600"
options={
lineNumbersMinChars: 2,
lineDecorationsWidth: 1,
highlightActiveIndentGuide: false,
cursorSmoothCaretAnimation: true,
readOnly: true,
contextmenu: false,
minimap: {
enabled: false
}
}
/>