TinyMce未在自定义工具栏"操作"中获取更新的状态值



我想访问TinyMCE的自定义工具栏操作中的更新状态值,但每次都得到初始值。

样本代码:

function App() {
const [state, setState] = React.useState(0);
const handleAction = (editor) => {
console.log("State", state); // getting initial state always
};
return (
<>
<button onClick={() => setState(state + 1)}>Add me</button>
<p>State: {state}</p>
<Editor
apiKey="XXX"
init={{
toolbar: "myCustomToolbarButton",
setup: (editor) => {
editor.ui.registry.addButton("myCustomToolbarButton", {
text: "My Custom Button",
onAction: (editor) => {
// alert("Button clicked!" + state)
handleAction(editor);
}
});
}
}}
/>
</>
);
}

我在这里创建了可复制的代码。

复制的步骤

  1. 单击"我的自定义按钮"按钮并检查控制台输出
  2. 通过单击"添加"按钮更新状态,该按钮将更新状态值
  3. 现在再次单击"我的自定义按钮",观察到我们仍然获得在创建组件时初始设置的初始状态

我想在自定义工具栏操作中访问更新状态,有什么方法可以做到这一点吗?或者任何解决方法都会非常有用?

您可以将状态传递给组件,然后使用ref:从props读取当前值

import React from "react";
import ReactDOM from "react-dom";
import { Editor } from "@tinymce/tinymce-react";
function App() {
const [state, setState] = React.useState(0);
const editor = React.useRef(null);
const handleAction = () => {
console.log(editor.current.props.state);
};
return (
<>
<button onClick={() => setState(state + 1)}>Add me</button>
<p>State: {state}</p>
<Editor
ref={editor}
state={state}
apiKey="XXX"
init={{
toolbar: "myCustomToolbarButton",
setup: (editor) => {
editor.ui.registry.addButton("myCustomToolbarButton", {
text: "My Custom Button",
onAction: handleAction
});
}
}}
/>
</>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

最新更新