使用 react-codemirror2 和 react-jsonschema-form 开始了一个新项目,也非常相似https://mozilla-services.github.io/react-jsonschema-form/
但是,当我的 codemirror 编辑器呈现 JSON 时,我将所有节目加载在一行上。我已经浏览了https://mozilla-services.github.io/react-jsonschema-form/的源代码,找不到任何与我所拥有的不同的东西。
我的源代码:
import React, { useEffect, useState } from "react";
import { UnControlled as CodeMirror } from "react-codemirror2";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/material.css";
import "codemirror/mode/javascript/javascript.js";
// components
const CodeEditorContainer = ({ code, onChange }) => {
const [codeEditorState, setCodeEditorState] = useState();
useEffect(() => {
setCodeEditorState(code);
}, [code]);
const cmOptions = {
theme: "default",
height: "auto",
viewportMargin: Infinity,
mode: {
name: "javascript",
json: true,
statementIndent: 2
},
lineNumbers: true,
lineWrapping: true,
indentWithTabs: false,
tabSize: 2
};
return (
<div className="panel panel-default">
<div className="panel-heading">Schema Editor</div>
<CodeMirror
value={codeEditorState}
options={cmOptions}
autoCursor={false}
onChange={(editor, data, value) => onChange(value)}
/>
</div>
);
};
export default CodeEditorContainer;
编辑:问题是我将 JSON 解析为字符串而不是
JSON.stringify(json)
我用了
JSON.stringify(json, null, 2)