You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Monaco-React-Editor无法校验用户HTML代码问题求助

解决Monaco-React 1.1.0无法捕获HTML代码错误的问题

核心问题

使用Monaco-React 1.1.0搭配React 18.2.0时,编辑器无法捕获HTML代码中的语法错误,onValidate回调也不会触发,即使官方文档说明该功能默认启用。

解决方案

1. 显式启用HTML语言验证

Monaco Editor的HTML验证依赖内置语言服务,部分版本需显式配置才能触发。在编辑器挂载时强制开启验证规则:

function handleEditorDidMount(editor, monaco) {
    editorRef.current = editor;
    // 配置HTML验证规则
    monaco.languages.html.htmlDefaults.setDiagnosticsOptions({
        validate: true,
        lint: {
            unclosedTags: true,
            mismatchedTags: true,
            unquotedAttributes: true
        }
    });
}

2. 修复onValidate的状态更新逻辑

原代码中使用setTimeout和陈旧状态更新错误列表,会导致状态不同步。改用函数式状态更新并过滤当前文件的错误标记:

function handleEditorValidation(markers) {
    const currentFileMarkers = markers.filter(
        marker => marker.resource.path === file.name
    );

    if (openedEditor === "html") {
        setHtmlErrors(prev => currentFileMarkers.map(m => ({
            line: m.startLineNumber,
            lineEnd: m.endLineNumber,
            col: m.startColumn,
            msg: m.message
        })));
    } else if (openedEditor === "css") {
        setCssErrors(prev => currentFileMarkers.map(m => ({
            line: m.startLineNumber,
            lineEnd: m.endLineNumber,
            col: m.startColumn,
            msg: m.message
        })));
    } else {
        setJsErrors(prev => currentFileMarkers.map(m => ({
            line: m.startLineNumber,
            lineEnd: m.endLineNumber,
            col: m.startColumn,
            msg: m.message
        })));
    }
}

3. 清理编辑器配置的重复项

原options对象重复设置了renderValidationDecorations,保留一个即可,并补充验证相关配置:

const options = {
    autoDetectHighContrast: true,
    screenReaderAnnounceInlineSuggestion: true,
    wordWrap: "on",
    renderValidationDecorations: "on",
    cursorWidth: 50,
    diagnosticsOptions: {
        validate: true
    }
};

4. 动态绑定编辑器语言和内容

原代码使用defaultLanguage和defaultValue,切换标签时无法动态更新编辑器状态,替换为language和value:

<Editor
    className='main-editor'
    theme='vs-dark'
    options={options}
    path={file.name}
    onMount={handleEditorDidMount}
    language={file.language}
    value={
        openedEditor === "html" ? html :
        openedEditor === "css" ? css : javascript
    }
    onValidate={handleEditorValidation}
    onChange={(value) => {
        openedEditor === "html" ? setHtml(value) :
        openedEditor === "css" ? setCss(value) : setJavascript(value);
    }}
    wordWrap={true}
/>

额外说明

  • 若升级Monaco-React到最新版本,部分配置可能会更简化,但需注意React 18的兼容性。
  • 可通过monaco.languages.html.htmlDefaults.setDiagnosticsOptions自定义更多HTML lint规则。

内容的提问来源于stack exchange,提问作者Ruination

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 03:27:57