自定义按钮中的 TinyMCE React 内容为空

TinyMCE React content in empty in custom button

在我的tinyMCE自定义按钮中,编辑器内容总是空的。

import React, { useEffect, useState } from "react";
import { Editor } from '@tinymce/tinymce-react';

const TINYMCEKEY = 'MY_SECRET_KEY';

const MyForm = () => {
   const [ editorContent, setEditorContent ] = useState("");

   useEffect(() => {
      const text = "This is a Test";
      setEditorContent(text);
   });

   const handleEditorChange = (content) => {
      setEditorContent(content);
   }

   return (
      <>
         <Editor
            apiKey={TINYMCEKEY}
            value={editorContent}
            init={{
               height: 600,
               menubar: false,
               branding: false,
               plugins: [
                  "print"
               ],
               setup: function (editor) {
                  editor.ui.registry.addButton('testBTN', {
                     text: "My Button",
                     onAction: function () {
                        console.log(editorContent); // It's always empty
                     }
                  });
               },
               toolbar1: "print | testBTN"
            }}
            onEditorChange={handleEditorChange}
         />
      </>
   );
}

export default MyForm;

我能够通过使用 ref.

来让它工作
const MyForm = () => {
  const [editorContent, setEditorContent] = useState("");
  const editor = useRef(null);

  const onButtonClick = () => {
    setEditorContent(editor.current.props.value);
  };

  const handleEditorChange = (content) => {
    setEditorContent(content);
  };

  return (
    <>
      <Editor
        ref={editor}
        apiKey={TINYMCEKEY}
        value={editorContent}
        init={{
          height: 600,
          menubar: false,
          branding: false,
          plugins: ["print"],
          setup: function (editor) {
            editor.ui.registry.addButton("testBTN", {
              text: "My Button",
              onAction: onButtonClick
            });
          },
          toolbar1: "print | testBTN"
        }}
        onEditorChange={handleEditorChange}
      />
    </>
  );
};

所以想法是将 ref 传递给 Editor 并使用此 ref 检索当前内容文本值。然后您可以将其保存在状态中或用它做任何您想做的事情。