React实现复制代码块到codeMirror代码编辑器中
背景介绍
某项目需要使用React实现点击右侧的参数列表后,将参数复制到代码编辑区中,实现参数或者代码块的快速输入。具体的实现效果如下图所示
准备工作
- 【React实现复制代码块到codeMirror代码编辑器中】安装codemirror,react-codemirror2
npm install react-codemirror2 codemirror --save
引入组件
import 'codemirror/lib/codemirror.css';
import 'codemirror/theme/material.css';
import {UnControlled as CodeMirror} from 'react-codemirror2';
require('codemirror/mode/shell/shell');
实现代码
{
this.instance = editor
}}
options={{
mode: 'shell',
theme: 'material',
lineNumbers: true,
autofocus: true,//自动获取焦点
styleActiveLine: true,//光标代码高亮
smartIndent: true,//自动缩进
start: true,
lineWrapping: true,
foldGutter: true,
}}
onChange={(editor, data, value) => {
this.setState({
commandLine: value,
})
}}
/>
handleParamCopy = (param) => {
const pos1 = this.instance.getCursor();
const pos2 = {
line: pos1.line,//行号
ch: pos1.ch //光标位置
}
const insertValue = "https://www.it610.com/article/${" + param + "} ";
this.instance.replaceRange(insertValue, pos2);
}
以上代码的关键点为
editorDidMount={editor => {
this.instance = editor
}}
通过editorDidMount将CodeMirror的ref获得,然后就可以在handleParamCopy函数中使用CodeMirror的各种方法。这种方法也适用于其他老的非控组件在React中使用。
推荐阅读
- 用Python实现屏幕截图详解
- 使用umi.js 3.0搭建React开发框架
- ASP.NetCore+VUE|ASP.NetCore+VUE 实现学生成绩管理系统(一)
- 解决react中label标签for报错问题
- Qt实现文本编辑器(一)
- vue项目中使用websocket的实现
- C++|C++ OpenCV实现银行卡号识别功能
- 面试官(Redis中字符串的内部实现方式是什么())
- javascript|JavaScript实现飞机大战
- React|【学习笔记】React+React全家桶学习笔记