下面我的代码有问题。当您单击add code按钮时,它会将代码添加到摩纳哥代码编辑器中,这是很棒的。但是,如果您在编辑器中键入更多代码或删除当前的内容,然后按“添加代码”按钮,则不会添加任何内容。只是空白而已。
当单击“添加代码”按钮时,是否有一种方法可以清除编辑器中的所有内容,并在单击按钮时添加setAddCode状态?
这是密码:
import { useState, useRef, useEffect } from "react";
import Editor from "@monaco-editor/react";
export default function IndexPage() {
const [input, setInput] = useState("");
const [addCode, setAddCode] = useState("# code goes here");
const editorRef = useRef(null);
function handleEditorDidMount(editor, monaco) {
setInput((editorRef.current = editor));
editorRef.current = editor;
}
return (
<div>
<div className="code-editor">
<Editor
width="100vh"
height="40vh"
theme="vs-dark"
fontSize="14"
defaultLanguage="python"
defaultValue=""
value={addCode}
onMount={handleEditorDidMount}
/>
</div>
<br />
<button onClick={() => setAddCode("print('Hello World!')")}>
Add code
</button>
</div>
);
}发布于 2022-10-26 00:55:12
编辑器组件的设置方式,只有当您传递不同的value支柱时,它才会更改编辑器中的值。它可能正在做一些类似于以下的事情:
const Editor = ({ value }) => {
const [codeToDisplay, setCodeToDisplay] = useState(value);
useEffect(() => {
setCodeToDisplay(value);
}, [value]);
// etc在父组件中,当您第一次调用setAddCode("print('Hello World!')")时,这将导致子组件看到其调用方式的不同-- value支柱发生了变化--因此它将知道要显示什么不同的东西,并适当地更新自己的内部状态。当您再次按下按钮时,addCode值将保持不变--编辑器组件看不到任何差异,因此不会更新。
要修复它,您可以从内部编辑器中侦听更改,方法是当编辑器中的代码发生变化时,使用它的更换道具更新父组件中的状态--这样,稍后单击按钮时,支柱将有所不同,编辑器将知道如何更新其内部状态。
export default function IndexPage() {
const [input, setInput] = useState("");
const [codeValue, setCodeValue] = useState("# code goes here");
const editorRef = useRef(null);
function handleEditorDidMount(editor, monaco) {
setInput((editorRef.current = editor));
editorRef.current = editor;
}
return (
<div>
<div className="code-editor">
<Editor
width="100vh"
height="40vh"
theme="vs-dark"
fontSize="14"
defaultLanguage="python"
defaultValue=""
value={codeValue}
onChange={(newValue) => { setCodeValue(newValue); }}
onMount={handleEditorDidMount}
/>
</div>
<br />
<button onClick={() => setCodeValue("print('Hello World!')")}>
Add code
</button>
</div>
);
}https://stackoverflow.com/questions/74201554
复制相似问题