如何检测TinyMCE编辑器初始化完成?useEffect未触发问题排查
问题原因
useRef的current属性变化不会触发组件重渲染,React也不会把它作为useEffect依赖的追踪目标。你在onInit里给editorRef.current赋值时,只是修改了ref对象的一个属性,组件并不会重新渲染,所以useEffect的依赖数组里的editorRef.current始终是初始的null,自然不会触发useEffect执行。
解决方法
方法1:直接在onInit回调里处理就绪逻辑
既然onInit本身就是编辑器初始化完成的回调,直接在这里执行你需要的操作就行,没必要绕useEffect:
import React, { useRef } from "react"; import { Editor } from "@tinymce/tinymce-react"; export default function App() { const editorRef = useRef(null); const handleEditorInit = (evt, editor) => { editorRef.current = editor; console.log("editor is ready"); // 这里写编辑器就绪后的逻辑,比如关闭加载动画 }; return ( <> <Editor onInit={handleEditorInit} initialValue="<p>This is the initial content of the editor.</p>" init={{ height: 500, menubar: false, plugins: [ "advlist autolink lists link image charmap print preview anchor", "searchreplace visualblocks code fullscreen", "insertdatetime media table paste code help wordcount", ], toolbar: "undo redo | formatselect | " + "bold italic backcolor | alignleft aligncenter " + "alignright alignjustify | bullist numlist outdent indent | " + "removeformat | help", content_style: "body { font-family:Helvetica,Arial,sans-serif; font-size:14px }", }} /> </> ); }
方法2:用状态追踪编辑器就绪状态
如果需要通过状态控制UI(比如切换加载动画和编辑器),可以用useState维护就绪状态,在onInit里更新状态,再用useEffect监听这个状态:
import React, { useRef, useState, useEffect } from "react"; import { Editor } from "@tinymce/tinymce-react"; export default function App() { const editorRef = useRef(null); const [isEditorReady, setIsEditorReady] = useState(false); useEffect(() => { if (isEditorReady) { console.log("editor is ready"); // 处理就绪后的逻辑 } }, [isEditorReady]); return ( <> {!isEditorReady && <div>加载中...</div>} <Editor onInit={(evt, editor) => { editorRef.current = editor; setIsEditorReady(true); }} initialValue="<p>This is the initial content of the editor.</p>" init={{ height: 500, menubar: false, plugins: [ "advlist autolink lists link image charmap print preview anchor", "searchreplace visualblocks code fullscreen", "insertdatetime media table paste code help wordcount", ], toolbar: "undo redo | formatselect | " + "bold italic backcolor | alignleft aligncenter " + "alignright alignjustify | bullist numlist outdent indent | " + "removeformat | help", content_style: "body { font-family:Helvetica,Arial,sans-serif; font-size:14px }", }} /> </> ); }
内容的提问来源于stack exchange,提问作者John Huang
相关产品推荐
相关产品推荐

