reactjs monaco-editor/react onClick事件未激发

ewm0tg9j  于 2023-02-08  发布在  React
关注(0)|答案(2)|浏览(226)

我在我的Next.js应用程序中使用monaco-editor/react,一切运行良好。我需要处理编辑器的onClick事件,但该事件从未触发。以下是我的代码:

import Editor from "@monaco-editor/react";
import { useRef, useState } from "react";

export default function MyEditor(){
    const editorRef = useRef(null);
    const [code,setCode]=useState("");

    function handleEditorDidMount(editor, monaco) {
        editorRef.current = editor;
    }

    function onChange(e) {
        setCode(e);
    }

    return(<Editor
            height="90vh"
            defaultLanguage="javascript"
            defaultValue="// some comment"
            value={code}
            onMount={handleEditorDidMount}
            onChange={onChange}
            onClick={() => {
              // this is never called
              alert("Clicked");
            }}
     />);
}
wr98u20j

wr98u20j1#

onClick可以被Editor包抑制。在这种情况下,也许你可以给予一试。

<div onClick={() => { alert('ddd' }}>
    <Editor ... />
  </div>

理论上,这种咔嗒声是无法抑制的。

bkkx9g8r

bkkx9g8r2#

这个问题让我太纠结了,到目前为止我还能控制点击事件和按键。因为没有鼠标点击事件,我只是简单地跟踪了点击事件并发出警报,这样用户就不能打开上下文菜单了。谢谢。

import Editor from "@monaco-editor/react";
import { useRef, useState } from "react";

export default function MyEditor(){
    const editorRef = useRef(null);
    const [code,setCode]=useState("");

    function handleEditorDidMount(editor, monaco) {
     editorRef.current = editor;
     editor.onKeyDown((event) => {
     console.log("event",event)
      const { keyCode, ctrlKey, metaKey } = event;
      if ((keyCode === 33 || keyCode === 52 || keyCode==93) && (metaKey || ctrlKey)){
        event.preventDefault();
        toast.show({
          status: "warning",
          title: "Don't copy paste your code.",
          placement: "top",
        });
      }
    });
    editor.onContextMenu((event)=>{
      console.log("event context",event)
    })
    
    editor.onMouseDown((event)=>{
      if(event?.event?.rightButton){
          alert("dont press right click")
          console.log("right click")
      }
    })
    }

    function onChange(e) {
        setCode(e);
    }

    return(<Editor
            height="90vh"
            defaultLanguage="javascript"
            defaultValue="// some comment"
            value={code}
            onMount={handleEditorDidMount}
            onChange={onChange}
            
     />);
}

相关问题