我已经实现了一个编辑器与tinymce包,我有 comments 插件.此外,我还构建了一个功能如下:当用户 Select 一个文本时,我将其存储在一个状态变量中,以便从tiny的内置创建函数中读取它,并将所有数据发送到我的后端.总的来说,我希望当用户 Select 一个文本来创建 comments 时,通过tiny的create函数将突出显示的文本发送到我的后端,但create函数只读取变量的初始状态,而不读取更新的值.代码ID如下:
import { Editor as EditorMce } from "@tinymce/tinymce-react";
//... some imports
function Editor() {
let [highlightedText, setHighlightedText] = useState("");
const tinycomments_create = (req, done, fail) => {
const { content, createdAt } = req;
console.log("highligt inside create function");
console.log(highlightedText); //This is always an empy string, the initial value
//and does not update when user highlights a text
fetch("my-backend-endpoint", {
method: "POST",
body: JSON.stringify({
content,
createdAt,
highlightedText,
}),
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
})
.then((response) => {
if (!response.ok) {
throw new Error("Failed to create comment");
}
return response.json();
})
.then((req2) => {
const conversationUid = req2.id;
done({ conversationUid });
})
.catch((e) => {
fail(e);
});
};
//... some existing code and I return the component
<EditorMce
value={session ? session.sessionText : ""}
onEditorChange={handleOnEditorChange}
init={{
init_instance_callback: (editor) => {
editor.on("MouseUp", function (e) {
if (e.view.getSelection().toString() !== "") {
setHighlightedText(e.view.getSelection().toString());
}
});
},
content_css: "writer",
height: "80%",
width: "95%",
plugins: [
"tinycomments",
"advlist",
"autolink",
"lists",
"link",
"image",
"charmap",
"preview",
"anchor",
"searchreplace",
"visualblocks",
"code",
"fullscreen",
"insertdatetime",
"media",
"table",
"code",
"help",
"wordcount",
],
menubar: "file edit view insert format tools tc",
menu: {
tc: {
title: "Comments",
items: "addcomment showcomments deleteallconversations",
},
},
toolbar:
"undo redo | fontsizeinput fontfamily | blocks | " +
"bold italic forecolor backcolor | alignleft aligncenter " +
"alignright alignjustify | bullist numlist outdent indent | " +
"removeformat | addcomment showcomments | help",
content_style:
"body { font-family:Helvetica,Arial,sans-serif; font-size:16px }" +
".tox-comments-visible span.tox-comment { background-color: #90EE90!important; }.tox-comments-visible span.tox-comment--active { background-color: black; }",
tinycomments_create,
tinycomments_reply,
tinycomments_edit_comment,
tinycomments_delete,
tinycomments_delete_all,
tinycomments_delete_comment,
tinycomments_lookup,
}}
/>
}
如何更新tinyComments_Create内的Highlight tedText的值.我已经try 了Use Callback挂钩,但没有结果.此外,我还try 在useEffect中添加tinyComments_Create,并在每次Highlight tedText更新时设置它,但再次没有结果. 对此有什么 idea 吗?