问题描述
我试图在单击按钮时提醒ace编辑器的最终值。我知道Ace编辑器有一个onChange事件,只是不确定如何将该值添加到我的 handleClick 函数中。
这是我当前的代码:
import ReactAce from "react-ace";
import React from "react";
import "ace-builds/src-noconflict/mode-python";
import "ace-builds/src-noconflict/theme-twilight";
function onChange(newValue) {
console.log("change",newValue);
}
function handleClick() {
alert();
}
function CodeEditor(props) {
return (
<>
<ReactAce
value={props.value}
mode="python"
theme="twilight"
showPrintMargin={false}
setReadOnly={false}
setValue={props.value}
fontSize={18}
style={{
height: "620px",width: "100%",}}
onChange={onChange}
/>
<button onClick={handleClick}>Run Code</button>
</>
);
}
export default CodeEditor;
解决方法
您可以使用useState挂钩来管理文本的状态。
function CodeEditor(props) {
// save the state here
const [ text,setText ] = useState('')
const handleClick = () => {
alert(text)
}
return (
<>
<ReactAce
value={props.value}
mode="python"
theme="twilight"
showPrintMargin={false}
setReadOnly={false}
setValue={props.value}
fontSize={18}
style={{
height: "620px",width: "100%",}}
// set the state when the value changes
onChange={(e) => setText(e.target.value)}
/>
<button onClick={() => handleClick()}>Run Code</button>
</>