React-ace: Ace编辑器仅绑定安装中的命令

创建于 2019-08-12  ·  5评论  ·  资料来源: securingsincity/react-ace

问题

如果将prop函数传递给react-ace,它将仅在AceEditor挂载处绑定该函数。 如果您的功能道具更改,它将不会使用您新更改的功能,仅会在第一个安装时传入该功能。

在此详细说明问题,包括所有可能的解决方案。

示例代码重现您的问题

(忽略错误)
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条评论

我遇到了这个问题,并通过使用getValue()从传递给命令的Editor中获取值来解决了这个问题。

因此,您需要更改handleSubmit函数。

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

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

感谢您的解决方法! 这是一个不错的临时解决方案,但仍然不能解决根本问题。 您不应该被迫将整个编辑器对象传递给父对象。 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(),
        },
      ]}/>
    )
}

在此问题解决之前,这里是上面讨论了两种解决方法的更多代码

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 等级

相关问题

dmavrin picture dmavrin  ·  3评论

ponelat picture ponelat  ·  3评论

tsmirnov picture tsmirnov  ·  4评论

nenadlukic picture nenadlukic  ·  6评论

Bobcui001 picture Bobcui001  ·  5评论