React-ace: エースエディタはマウント時にのみコマンドをバインドします

作成日 2019年08月12日  ·  5コメント  ·  ソース: securingsincity/react-ace

問題

prop関数をreact-aceに渡すと、AceEditorマウントでのみ関数がバインドされます。 関数propが変更された場合、新しく変更された関数は使用されず、最初のマウントで渡された関数のみが使用されます。

考えられる解決策を含め、ここで問題を詳しく説明します。

問題を再現するためのサンプルコード

(エラーは無視してください)
Edit relaxed-goldwasser-qprrd

参考文献

進捗状況:#

Documentation bug question

最も参考になるコメント

@ 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(),
        },
      ]}/>
    )
}

全てのコメント5件

私はこの問題にぶつかったから値を取得することにより、その周りになったEditor使用してコマンドに渡されるgetValue()

したがって、あなたの場合、 handleSubmit関数を変更します。

const handleSubmit = (editor) => {
  const text = editor.getValue();
  window.alert("You submitted the text: " + text);
};

https://codesandbox.io/s/confident-neumann-99zmk

回避策をありがとう! それはまともな一時的な解決策ですが、それでも根本的な問題を解決することはできません。 エディタオブジェクト全体を親に渡すことを強制されるべきではありません。 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つの回避策のコードをさらに示します。

editor.getValue()[よりクリーンな回避策]

// `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()),
      }]}
    />
  );
}

useRef

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),
      }]}
    />
  );
}
このページは役に立ちましたか?
0 / 5 - 0 評価