避免@monaco-editor/react自定义代码提示中的常见陷阱
2024-01-31 22:36:14
@monaco-editor/react 自定义代码提示踩坑指南
对于初入职场的程序员来说,在项目开发中使用第三方库是不可避免的。最近,我在项目中使用了 @monaco-editor/react
来实现代码编辑器功能。然而,在尝试自定义代码提示时,却遇到了不少坑,现分享给大家,希望可以帮助到有类似需求的开发者。
1. 使用错误的 provider
刚开始,我按照文档中的指示,在根组件中使用 <MonacoProvider>
。但是,当我尝试使用 editor.addAction()
方法添加自定义代码提示时,却遇到了 undefined
的错误。后来,经过一番排查,我发现应该使用 <EditorProvider>
,而不是 <MonacoProvider>
。
2. 忘记导入提示建议
自定义代码提示需要使用 SuggestController
类,但是我忘记在组件中导入它。正确的做法是在 import
语句中加入 SuggestController
类。
import { SuggestController } from "@monaco-editor/react";
3. 模型未加载
在添加代码提示之前,需要确保编辑器模型已经加载。否则,editor.addAction()
方法会抛出 undefined
错误。解决方法是在 useEffect
钩子中添加对模型加载状态的监听。
useEffect(() => {
if (editorRef.current && editorRef.current.getModel()) {
// 添加代码提示
const suggestController = new SuggestController(editorRef.current);
}
}, [editorRef]);
4. 回调中使用错误的模型
在自定义代码提示时,需要在回调中使用正确的模型。否则,会提示 editor
为 undefined
。正确的做法是在回调中使用 getModel()
方法获取模型。
suggestController.triggerSuggest(false, model => {
// 在模型中添加提示建议
});
5. 提示建议未展示
如果代码提示未展示,可以检查是否启用了建议小部件。可以通过调用 editor.hasWidget()
方法来检查。如果为 false
,则需要启用建议小部件。
suggestController.triggerSuggest(false, model => {
// 启用建议小部件
editor.getContribution("editor.contrib.suggestController").showSuggestWidget();
});
通过踩过这些坑,我最终成功实现了自定义代码提示功能。希望这份踩坑日记能够帮助其他开发者在使用 @monaco-editor/react
时少走弯路。