prop関数をreact-aceに渡すと、AceEditorマウントでのみ関数がバインドされます。 関数propが変更された場合、新しく変更された関数は使用されず、最初のマウントで渡された関数のみが使用されます。
考えられる解決策を含め、ここで問題を詳しく説明します。
進捗状況:#
私はこの問題にぶつかったから値を取得することにより、その周りになったEditor
使用してコマンドに渡されるgetValue()
。
したがって、あなたの場合、 handleSubmit
関数を変更します。
const handleSubmit = (editor) => {
const text = editor.getValue();
window.alert("You submitted the text: " + text);
};
回避策をありがとう! それはまともな一時的な解決策ですが、それでも根本的な問題を解決することはできません。 エディタオブジェクト全体を親に渡すことを強制されるべきではありません。 Ace Editorコンポーネントは、マウント時にコマンドをバインドするだけではありません。 渡されるコマンドを変更すると、更新されたコマンドでコンポーネントが更新されます。
関数コンポーネントの現在の回避策は、 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(),
},
]}/>
)
}
これが修正されるまで、上記の2つの回避策のコードをさらに示します。
// `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どうやってこれを機能させたのですか? 私が試した次の例を使用すると、それは解決策として機能していないようですか?