import React from 'react';
import logo from './logo.svg';
import './App.css';
import MonacoEditor from 'react-monaco-editor';
import { useRef, useState,useEffect } from 'react';
function App() {
const editorRef = useRef(null);
const monacoRef = useRef(null);
const decorationsRef = useRef([]);
const handleEditorDidMount = (editor: any, monaco: any) => {
editorRef.current = editor;
monacoRef.current = monaco;
// Add an event listener for cursor position changes
editor.onDidChangeCursorSelection(() => {
const selection = editor.getSelection();
// if (selection.isEmpty()) {
// // Remove decorations if selection is empty
// editor.deltaDecorations(decorationsRef.current, []);
// return;
// }
const lineNumber = selection.positionLineNumber;
const lineContent = editor.getModel().getLineContent(lineNumber);
if (lineContent !== "") {
// Add decoration if the line starts with 'var'
const newDecorations = editor.deltaDecorations(decorationsRef.current, [
{
range: new monaco.Range(lineNumber, 1, lineNumber, 1),
options: {
isWholeLine: true,
afterContentClassName: 'myAfterContentDecoration'
}
}
]);
decorationsRef.current = newDecorations;
} else {
// Remove decorations if the line does not start with 'var'
editor.deltaDecorations(decorationsRef.current, []);
}
});
};
useEffect(() => {
// Define custom styles for the decorations
const style = document.createElement('style');
style.innerHTML = `
.myAfterContentDecoration::after {
content: ' // 备注';
color: green;
font-weight: bold;
}
`;
document.head.appendChild(style);
}, []);
const clickButton = () => {
if(monacoRef.current) { // null
console.log(monacoRef.current) // never
}
}
return (
<div style={{'margin':'100px auto', 'width': '800px'}}>
<MonacoEditor
value={"112233"}
editorDidMount={handleEditorDidMount}
/>
<button onClick={clickButton}>点击</button>
</div>
);
}
export default App;
在代码:clickButton
里面, if(monacoRef.current)
这里是null
,但是在console.log(monacoRef.current)
里面是never
:
因为是never
, 就不能点进行使用属性了。
请问这个问题应该如何处理呢?
const monacoRef = useRef<XXX>(null);
在 XXX 的位置补上泛型。https://github.com/react-monaco-editor/react-monaco-editor/blob/master/src/editor.tsx#L25