monaco editor 在react中的使用

1. 首先先导入monaco editor

npm install monaco-editor

// npm install monaco-editor --force   // 版本冲突? 强行安装

2. 在react中使用

期望效果如下



3. 我遇到的问题 : 输入json数据后 未格式化 , json数据仍然一行展示

    我遇到的问题 : 直接输入json数据会白屏报错 

    我遇到的问题 :  直接更改编辑器中的代码时 只能一次输入一个字段


完整代码及解决方法如下
 

import * as monaco from 'monaco-editor' // 引入

----------js 部分------------------------- 

const editorRef = useRef(null)

const [code, setCode] = useState('console.log("Hello, world!");')

const debounce = (func, wait) => {   // 防抖更新代码状态的函数
    let timeout
    return (...args) => {
      clearTimeout(timeout)
      timeout = setTimeout(() => {
        func.apply(this, args)
      }, wait)
    }
}

const debouncedSetCode = useCallback(  // 防抖更新代码状态的函数
    debounce(newCode => {
      setCode(newCode)
    }, 300),
    []
)


useEffect(() => {
    if (!editorRef.current) {
      console.error('editorRef.current is null')
      return // 早期返回,避免创建编辑器
    }

    const editor = monaco.editor.create(editorRef.current, {
      value: code,
      language: 'json',
      theme: 'hc-black' // 主题可选: 'vs', 'vs-dark', 'hc-black'
    })

    // 编辑器内容可编辑
    editor.updateOptions({ readOnly: false })

    // 监听代码变化
    editor.onDidChangeModelContent(() => {
      // setCode(editor.getValue())   // 直接更改编辑器中的代码 只能更改一个字段
         debouncedSetCode(editor.getValue())  // 这样就能输入多字段了 
         hyy(editor.getValue())  // 一个不存在的方法名 居然也可以输入多字段 且不报错 不明白
    })

    // 格式化操作
    const formatAction = editor.getAction('editor.action.formatDocument')
    if (formatAction) {
      formatAction.run()
    }

    return () => {
      editor.dispose() // 组件卸载时销毁编辑器实例
    }
 }, [code])

  const formatJson = code => {           // 封装了一个格式化函数
    try {
      const parsedJson = JSON.parse(code)
      const prettyJson = JSON.stringify(parsedJson, null, 2)
      editorRef.current.setValue(prettyJson)
      setCode(prettyJson)
    } catch (error) {
      console.error('Formatting error:', error)
    }
  }

  useEffect(() => {
    let aaa = {
      messages: [
        {
          text: 'Hello, how are you?',
          files: []
        }
      ]
    }

    let newCode
    switch (activeKey2) {
      case '1':
        newCode = 'console.log("Hello, world!");'
        break
      case '2':
        newCode = '{title: hyy , dataIndex: age}'
        break
      case '3':
        newCode = JSON.stringify(aaa, null, 2)   // json转成字符串就不会报错了,且需加上null, 2 让其具备格式化样式
        break
      case '4':
        newCode = '{title: hyy 456 , dataIndex: age}'
        break
      default:
        newCode = 'console.log("Hello, world!");'
        break
    }

    // 更新代码并格式化
    setCode(newCode)
    formatJson(newCode) // 调用格式化函数
  }, [activeKey2])  



  const items2 = [
    {
      key: '1',
      label: '响应体'
    },
    {
      key: '2',
      label: '响应头'
    },
    {
      key: '3',
      label: '实际请求'
    },
    {
      key: '4',
      label: '提取'
    },
    {
      key: '5',
      label: '断言'
    }
  ]
  const [activeKey2, setActiveKey2] = useState('1') // 切换tabs

-----------html 部分----------------

   <Tabs
            defaultActiveKey='1'
            items={items2}
            onChange={key => setActiveKey2(key)}
          ></Tabs>
     <div
            ref={editorRef}
            style={{
              height: '500px',
              paddingTop: '20px',
              borderRadius: '10px'
            }}
    />


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值