Leo*_*ssi 2 javascript typescript reactjs typescript-typings monaco-editor
以下代码片段可以与 React + Javascript 配合使用:
import React, { useRef } from "react";
import Editor from "@monaco-editor/react";
function App() {
const editorRef = useRef(null);
function handleEditorDidMount(editor, monaco) {
editorRef.current = editor;
}
function showValue() {
alert(editorRef.current?.getValue());
}
return (
<>
<button onClick={showValue}>Show value</button>
<Editor
height="90vh"
defaultLanguage="javascript"
defaultValue="// some comment"
onMount={handleEditorDidMount}
/>
</>
);
}
export default App;
Run Code Online (Sandbox Code Playgroud)
我需要在 React + Typescript 应用程序中使用它,所以我必须添加类型。
应该用于什么类型editor?
尝试过这样的:
function handleEditorDidMount(editor: HTMLInputElement) {
editorRef?.current = editor;
}
function showValue() {
// eslint-disable-next-line no-alert
alert(editorRef?.current?.getValue());
}
Run Code Online (Sandbox Code Playgroud)
对于第一种方法,错误是:
The left-hand side of an assignment expression may not be an optional property access.ts(2779)
const editorRef: React.MutableRefObject<null>
Run Code Online (Sandbox Code Playgroud)
对于第二个:
Property 'getValue' does not exist on type 'never'.ts(2339)
Run Code Online (Sandbox Code Playgroud)
有什么建议么?
进口类型onMount
import MonacoEditor, { OnMount } from "@monaco-editor/react";
Run Code Online (Sandbox Code Playgroud)
如果您将鼠标悬停在onMount:
type OnMount = (editor: monaco.editor.IStandaloneCodeEditor, monaco: Monaco) => void
Run Code Online (Sandbox Code Playgroud)
在handleDidMount上使用它:
const handleEditorDidMount:OnMount=(编辑器) { editorRef?.current = 编辑器; }
如果你看到类型,handleEditorDidMount需要 2 个参数
const handleEditorDidMount:OnMount=(editor,_monaco) {
editorRef?.current = editor;
}
Run Code Online (Sandbox Code Playgroud)
由于您使用的是OnMount类型,因此 args 类型将由打字稿推断:
editor: editor.IStandaloneCodeEditor
Run Code Online (Sandbox Code Playgroud)