首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在nextjs中为javascript语言在react-codemirror编辑器中启用语法验证

如何在nextjs中为javascript语言在react-codemirror编辑器中启用语法验证
EN

Stack Overflow用户
提问于 2021-10-11 15:51:36
回答 1查看 198关注 0票数 0

我在我的Next.js应用程序中使用react-codemirror2编辑器。默认情况下,编辑器会标记语法验证错误和警告。我想确保当用户保存代码时,代码中没有语法错误。我需要访问验证结果,我不知道如何实现这一点。下面是我的代码:

代码语言:javascript
复制
import React, { Fragment } from "react";
let CodeMirror;
export default class Editor extends React.Component {
  state = {
    render: false,
    code: "",
  };
  componentDidMount = () => {
    CodeMirror = require("react-codemirror2");
    require("codemirror/lib/codemirror.css");
    require("codemirror/theme/eclipse.css");
    require("codemirror/addon/lint/lint.css");
    require("codemirror/addon/hint/show-hint.css");
    require("codemirror/mode/javascript/javascript.js");
    require("codemirror/addon/lint/javascript-lint");
    require("codemirror/addon/lint/lint.js");
    require("codemirror/addon/hint/javascript-hint");
    const { JSHINT } = require("jshint");
    window.JSHINT = JSHINT;
    this.setState({ render: true });
  };
  SaveCode() {
    // here I need to validate the [this.state.code]
    // if there is no syntax error then save it
  }
  render() {
    if (!this.state.render) return null;
    const { UnControlled } = CodeMirror;
    return (
      <>
        <UnControlled
          value={this.state.code}
          onBeforeChange={(a, b, value) => {
            this.setState({ code:value });
          }}
          options={{
            readOnly: false,
            mode: "javascript",
            theme: "eclipse",
            lineNumbers: true,
            lint: true,
          }}
        />
        <div style={{ padding: "10px 25px 25px", textAlign: "right" }}>
          <button onClick={this.SaveCode}>Save</button>
        </div>
      </>
    );
  }
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-11 20:18:46

您可以使用onUpdateLinting函数接收内联错误。更改CodeMirror组件的options属性中的lint字段,如下所示:

代码语言:javascript
复制
lint: {
  onUpdateLinting: this.handleErrors,
},
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69529102

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档