Reac16+Monaco打造代码编辑器(前端部分)

本文介绍如何利用React和Monaco编辑器创建一个代码编辑器,重点讲述SelectBox.js的选择器实现,json数据的处理,以及在Index.js和EditorBody.js中的应用。通过编辑器主题的设置和monaco-editor-webpack-plugin,实现了代码提示等功能,但Monaco仅支持部分语言的代码补全,开发者可自定义接口扩展其他语言的支持。

效果图

在这里插入图片描述
在这里插入图片描述

实现

这里小编只讲编辑器的主体部分,及两个选择框以及编辑器部分。
首先是选择器,毕竟主体的编辑器需要通过选择器来改变样式以及提供语言高亮等支持

SelectBox.js
import React from 'react';
import {
   
    Select } from 'element-react';
import {
   
    Layout } from 'element-react';
import 'element-theme-default';
import valueData from '../../../jsondata/editor-data.json'

class SelectBox extends React.Component{
   
   
    constructor(props) {
   
   
        super(props);
        this.state = {
   
   
            //支持的语言
            options: [
                {
   
   
                    value: '选项1',
                    label: 'apex',
                },
                {
   
   
                    value: '选项2',
                    label: 'azcli',
                },
                {
   
   
                    value: '选项3',
                    label: 'bat',
                },
                {
   
   
                    value: '选项4',
                    label: 'c'
                },
                {
   
   
                    value: '选项5',
                    label: 'clojure',
                },
                {
   
   
                    value: '选项6',
                    label: 'coffeescript',
                },
                {
   
   
                    value: '选项7',
                    label: 'cpp',
                },
                {
   
   
                    value: '选项8',
                    label: 'csharp',
                },
                {
   
   
                    value: '选项9',
                    label: 'csp',
                },
                {
   
   
                    value: '选项10',
                    label: 'css',
                },
                {
   
   
                    value: '选项11',
                    label: 'dockerfile',
                },
                {
   
   
                    value: '选项12',
                    label: 'fsharp',
                },
                {
   
   
                    value: '选项13',
                    label: 'go',
                },
                {
   
   
                    value: '选项14',
                    label: 'handlebars',
                },
                {
   
   
                    value: '选项15',
                    label: 'html',
                },
                {
   
   
                    value: '选项16',
                    label: 'ini',
                },
                {
   
   
                    value: '选项17',
                    label: 'java',
                },
                {
   
   
                    value: '选项18',
                    label: 'javascript',
                },
                {
   
   
                    value: '选项19',
                    label: 'json',
                },
                {
   
   
                    value: '选项20',
                    label: 'less',
                },
                {
   
   
                    value: '选项21',
                    label: 'lua',
                },
                {
   
   
                    value: '选项22',
                    label: 'markdown',
                },
                {
   
   
                    value: '选项23',
                    label: 'msdax',
                },
                {
   
   
                    value: '选项24',
                    label: 'mysql',
                },
                {
   
   
                    value: '选项25',
                    label: 'objective',
                },
                {
   
   
                    value: '选项26',
                    label: 'pascal',
                },
                {
   
   
                    value: '选项27',
                    label: 'perl',
                },
                {
   
   
                    value: '选项28',
                    label: 'pgsql',
                },
                {
   
   
                    value: '选项29',
                    label: 'php',
                },
                {
   
   
                    value: '选项30',
                    label: 'postiats',
                },
                {
   
   
                    value: '选项31',
                    label: 'powerquery',
                },
                {
   
   
                    value: '选项32',
                    label: 'powershell',
                },
                {
   
   
                    value: '选项33',
                    label: 'pug',
                },
                {
   
   
                    value: '选项34',
                    label: 'python',
                },
                {
   
   
                    value: '选项35',
                    label: 'r',
                },
                {
   
   
                    value: '选项36',
                    label: 'razor',
                },
                {
   
   
                    value: '选项37',
                    label: 'redis',
                },
                {
   
   
                    value: '选项38',
                    label: 'redshift',
                },
                {
   
   
                    value: '选项39',
                    label: 'ruby',
                },
                {
   
   
                    value: '选项40',
                    label: 'rust',
                },
                {
   
   
                    value: '选项41',
                    label: 'sb',
                },
                {
   
   
                    value: '选项42',
                    label: 'scheme',
                },
                {
   
   
                    value: '选项43',
                    label: 'scss',
                },
                {
   
   
                    value: '选项44',
                    label: 'shell',
                },
                {
   
   
                    value: '选项45',
                    label: 'sol',
                },
                {
   
   
                    value: '选项46',
                    label: 'sql',
                },
                {
   
   
                    value: '选项47',
                    label: 'st',
                },
                {
   
   
                    value: '选项48',
                    label: 'swift',
                },
                {
   
   
                    value: '选项49',
                    label: 'typescript',
                },
                {
   
   
                    value: '选项50',
                    label: 'vb',
                },
                {
   
   
                    value: '选项51',
                    label: 'xml',
                },
                {
   
   
                    value: '选项52',
                    label: 'yaml'
                }
            ],
            //支持的主题
            theme: [
                {
   
   
                    value: '选项1',
                    label: 'Visual Studio',
                },
                {
   
   
                    value: '选项2',
                    label: 'Visual Studio Dark',
                },
                {
   
   
                    value: '选项3',
                    label: 'Hight Contrast Dark',
                },
            ],
            value: ''
        };
    }

    //改变主题,通过Select的onChnage触发
    handleSelectTheme(event){
   
   
        //根据选择设置对主题的值
        let selectval = '';
        if (event === '选项1') {
   
   
            selectval = 'vs';
        } else if (event === '选项2') {
   
   
            selectval = 'vs-dark';
        } else if (event === '选项3') {
   
   
            selectval = 'hc-black';
        }
        //通过调用父组件的方法,修改父组件中的state
        this.props.ChangeTheme(selectval);
    }

    //改变语言,通过Select的onChnage触发
    handleSelectLanguage(event){
   
   
        //通过调用父组件的方法,修改父组件中的state,修改的是语言
        this.props.ChangeLanguage(event);
        for(let i = 0;i < valueData.values.length;i++)
        {
   
   
            if (valueData.values[i].language === event)
            {
   
   
                //通过调用父组件的方法,修改父组件中的state
                //修改的是编辑框中显示的内容
                //这里是用的是json数据
                this.props.ChangeValue(valueData.values[i].value);
            }
        }
    }

    render() {
   
   
        return (
            <div>
                <Layout.Row>
                    <Layout.Col span="12">
                        <div className="grid-content bg-purple-light">
                            <span>主题:</span>
                            <Select value={
   
   this.state.value} placeholder="请选择" onChange={
   
   this.handleSelectTheme.bind(this)}>
                                {
   
   
                                    this.state.theme.map(el => {
   
   
                                        return <Select.Option  key={
   
   el.value} label={
   
   el.label} value={
   
   el.value}/>
                                    })
                                }
                            </Select>
                        </div>
                    </Layout.Col>
                    <Layout.Col span="12">
                        <div className="grid-content bg-purple-light">
                            <span>语言:</span>
                            <Select value={
   
   this.state.value} placeholder="请选择" onChange={
   
   this.handleSelectLanguage.bind(this)}>
                                {
   
   
                                    this.state.options.map(el => {
   
   
                                        return <Select.Option  key={
   
   el.value} label={
   
   el.label} value={
   
   el.label}/>
                                    })
                                }
                            </Select>
                        </div>
                    </Layout.Col>
                </Layout.Row>
            </div>
        );
    }
}

export default SelectBox;

json数据
{
   
   
  "values": [
    {
   
   
      "language": "apex",
      "value": "/* Using a single database query, find all the leads in\n    the database that have the same email address as any\n    of the leads being inserted or updated. */\nfor (Lead lead : [SELECT Email FROM Lead WHERE Email IN :leadMap.KeySet()]) {\n    Lead newLead = leadMap.get(lead.Email);\n    newLead.Email.addError('A lead with this email address already exists.');\n}\n"


    },
    {
   
   
      "language": "azcli",
      "value": "# Create a resource group.\naz group create --name myResourceGroup --location westeurope\n\n# Create a new virtual machine, this creates SSH keys if not present.\naz vm create --resource-group myResourceGroup --name myVM --image UbuntuLTS --generate-ssh-keys"
    },
    {
   
   
      "language": "bat",
      "value": "rem *******Begin Comment**************\nrem This program starts the superapp batch program on the network,\nrem directs the output to a file, and displays the file\nrem in Notepad.\nrem *******End Comment**************\n@echo off\nif exist C:\\output.txt goto EMPTYEXISTS\nsetlocal\n\tpath=g:\\programs\\superapp;%path%\n\tcall superapp>C:\\output.txt\nendlocal\n:EMPTYEXISTS\nstart notepad c:\\output.txt"
    },
    {
   
   
      "language": "clojure",
      "value": "(ns game-of-life\n  \"Conway's Game of Life, based on the work of\n  Christophe Grand (http://clj-me.cgrand.net/2011/08/19/conways-game-of-life)\n  and Laurent Petit (https://gist.github.com/1200343).\")\n\n;;; Core game of life's algorithm functions\n\n(defn neighbors\n  \"Given a cell's coordinates `[x y]`, returns the coordinates of its\n  neighbors.\"\n  [[x y]]\n  (for [dx [-1 0 1]\n        dy (if (zero? dx)\n             [-1 1]\n             [-1 0 1])]\n    [(+ dx x) (+ dy y)]))\n\n(defn step\n  \"Given a set of living `cells`, computes the new set of living cells.\"\n  [cells]\n  (set (for [[cell n] (frequencies (mapcat neighbors cells))\n             :when (or (= n 3)\n                       (and (= n 2)\n                            (cells cell)))]\n         cell)))\n\n;;; Utility methods for displaying game on a text terminal\n\n(defn print-grid\n  \"Prints a `grid` of `w` columns and `h` rows, on *out*, representing a\n  step in the game.\"\n  [grid w h]\n  (doseq [x (range (inc w))\n          y (range (inc h))]\n    (when (= y 0) (println))\n    (print (if (grid [x y])\n             \"[X]\"\n             \" . \"))))\n\n(defn print-grids\n  \"Prints a sequence of `grids` of `w` columns and `h` rows on *out*,\n  representing several steps.\"\n  [grids w h]\n  (doseq [grid grids]\n    (print-grid grid w h)\n    (println)))\n\n;;; Launches an example grid\n\n(def grid\n  \"`grid` represents the initial set of living cells\"\n  #{[2 1] [2 2] [2 3]})\n\n(print-grids (take 3 (iterate step grid)) 5 5)"
    },
    {
   
   
      "language": "coffeescript",
      "value": "\"\"\"\nA CoffeeScript sample.\n\"\"\"\n\nclass Vehicle\n  constructor: (@name) =>\n  \n  drive: () =>\n    alert \"Conducting #{@name}\"\n\nclass Car extends Vehicle\n  drive: () =>\n    alert \"Driving #{@name}\"\n\nc = new Car \"Brandie\"\n\nwhile notAtDestination()\n  c.drive()\n\nraceVehicles = (new Car for i in [1..100])\n\nstartRace = (vehicles) -> [vehicle.drive() for vehicle in vehicles]\n\nfancyRegExp = ///\n\t(\\d+)\t# numbers\n\t(\\w*)\t# letters\n\t$\t\t# the end\n///\n"
    },
    {
   
   
      "language": "cpp",
      "value": "#include \"pch.h\"\n#include \"Direct3DBase.h\"\n\nusing namespace Microsoft::WRL;\nusing namespace Windows::UI::Core;\nusing namespace Windows::Foundation;\n\n// Constructor.\nDirect3DBase::Direct3DBase()\n{\n}\n\n// Initialize the Direct3D resources required to run.\nvoid Direct3DBase::Initialize(CoreWindow^ window)\n{\n    m_window = window;\n    \n    CreateDeviceResources();\n    CreateWindowSizeDependentResources();\n}\n\n// These are the resources that depend on the device.\nvoid Direct3DBase::CreateDeviceResources()\n{\n    // This fla
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值