likes
comments
collection
share

React实现复制代码块到codeMirror代码编辑器中

作者站长头像
站长
· 阅读数 41

背景介绍

某项目需要使用React实现点击右侧的参数列表后,将参数复制到代码编辑区中,实现参数或者代码块的快速输入。具体的实现效果如下图所示React实现复制代码块到codeMirror代码编辑器中

准备工作

  1. 安装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');

实现代码

<CodeMirror
                    value={commandLine}
                    editorDidMount={editor => {
                      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 = " ${" + param + "} ";
    this.instance.replaceRange(insertValue, pos2);
  }

以上代码的关键点为

editorDidMount={editor => {
                      this.instance = editor
                    }}

通过editorDidMount将CodeMirror的ref获得,然后就可以在handleParamCopy函数中使用CodeMirror的各种方法。这种方法也适用于其他老的非控组件在React中使用。

转载自:https://segmentfault.com/a/1190000041512665
评论
请登录