如果将prop函数传递给react-ace,它将仅在AceEditor挂载处绑定该函数。 如果您的功能道具更改,它将不会使用您新更改的功能,仅会在第一个安装时传入该功能。
在此详细说明问题,包括所有可能的解决方案。
进展:
我遇到了这个问题,并通过使用getValue()
从传递给命令的Editor
中获取值来解决了这个问题。
因此,您需要更改handleSubmit
函数。
const handleSubmit = (editor) => {
const text = editor.getValue();
window.alert("You submitted the text: " + text);
};
感谢您的解决方法! 这是一个不错的临时解决方案,但仍然不能解决根本问题。 您不应该被迫将整个编辑器对象传递给父对象。 Ace编辑器组件不仅应在安装时绑定您的命令。 如果更改了传入的命令,它将使用更新后的命令更新组件。
函数组件中的当前解决方法是使用useRef
并将() => referencedFunction.current()
分配为exec
@ FMS-Cat您是如何工作的? 使用我尝试的以下示例,它似乎无法解决问题?
function Example() {
function save() { ... }
const ref = useRef(save)
return (
<AceEditor commands={[
{
name: 'save',
bindKey: {
win: 'Ctrl-enter',
mac: 'Cmd-enter',
},
exec: () => ref.current(),
},
]}/>
)
}
在此问题解决之前,这里是上面讨论了两种解决方法的更多代码
// `onSave` shouldn't have to pass the content
// back up the chain since onChange already did that,
// hence calling this a workaround.
function Example({ content, onChange, onSave }) {
return (
<AceEditor
content={content}
onChange={c => onChange(c)}
commands={[{
name: 'save',
bindKey: { win: 'Ctrl-enter', mac: 'Cmd-enter' },
exec: editor => onSave(editor.getValue()),
}]}
/>
);
}
function Example({ content, onChange, onSave }) {
const editor = useRef(null)
return (
<AceEditor
ref={editor}
content={content}
onChange={c => onChange(c)}
commands={[{
name: 'save',
bindKey: { win: 'Ctrl-enter', mac: 'Cmd-enter' },
exec: () => onSave(editor.current.props.value),
}]}
/>
);
}
最有用的评论
@ FMS-Cat您是如何工作的? 使用我尝试的以下示例,它似乎无法解决问题?