所以我尝试将代码编辑器插入我的网络应用程序中。 我正在尝试导入并添加 Codemirror 的实例。 每次我为 CodeMirror 组件添加 JSX 代码时,它都会重复。 这是我的组件代码。
import { Controlled as ControlledEditor } from "react-codemirror2";
import "codemirror/lib/codemirror.css";
import "codemirror/theme/material.css";
require("codemirror/mode/xml/xml");
require("codemirror/mode/javascript/javascript");
const ProblemSolving = () => {
return (
<div className="editor-container">
<div className="editor-title">
Hello World
</div>
<ControlledEditor
value="var myVariable = 5"
options={{
lineWrapping: true,
lint: true,
mode: "javascript",
lineNumbers: true
}}
/>
</div>
);
};
export default ProblemSolving;
如图所示,有两个编辑器正在渲染。 一个已输入我设置的默认值,另一个具有空白行。 我不确定为什么会发生这种情况。
这个问题是由React18中的一个新特性引起的:https://reactjs.org/docs/strict-mode.html#ensuring-reusable-state简单地删除了编辑器dom,应该有更合适的方法。
function App() {
const editor = useRef()
const wrapper = useRef()
const editorWillUnmount = () => {
editor.current.display.wrapper.remove()
wrapper.current.hydrated = false
}
return (
<div className="App">
<CodeMirror
value='<h1>I ♥ react-codemirror2</h1>'
ref={wrapper}
options={{
mode: 'xml',
theme: 'material',
lineNumbers: true
}}
onChange={(editor, data, value) => {
}}
editorDidMount={(e) => editor.current = e}
editorWillUnmount={editorWillUnmount}
/>
</div>
);
}
或者删除index.js中的React.StrictMode
<React.StrictMode>
<App />
</React.StrictMode>
我使用了uiwjs react-codemirror并找到了所有功能