React/Next.js集成TinyMCE编辑器遇TypeError问题求助
修复TinyMCE集成时的"TypeError: editor1 is null"错误
你的问题出在两个关键地方:
- 在
handleSubmit函数内部重新声明了editor变量,直接覆盖了外部用来存储编辑器实例的变量,导致调用editor.getContent()时拿到的是你刚声明的null值 - 没有用React的
useRef来持久化编辑器实例,函数组件中普通变量会在每次渲染时重置,无法保留编辑器的引用
修复步骤:
- 导入React的
useRef钩子 - 用
useRef创建一个持久化的引用存储编辑器实例 - 修改
onInit回调,将编辑器实例赋值给ref的current属性 - 在
handleSubmit中通过ref的current获取编辑器实例,先判断实例存在再调用方法
修复后的完整代码:
import { useRef } from 'react'; import Editor from '@tinymce/tinymce-react'; const YourComponent = () => { // 创建ref存储编辑器实例 const editorRef = useRef<any>(null); const handleSubmit = (e: any) => { e.preventDefault(); // 先判断编辑器实例是否存在 if (editorRef.current) { const content = editorRef.current.getContent(); const data = { first: e.target.name.value, last: e.target.cat_name.value, content: content, }; // 这里可以处理data,比如提交到后端 console.log(data); } }; return ( <form onSubmit={handleSubmit}> {/* 表单其他输入框 */} <input name="name" type="text" /> <input name="cat_name" type="text" /> <Editor onInit={(evt, ed) => editorRef.current = ed} 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 }' }} /> <button type="submit">提交</button> </form> ); }; export default YourComponent;
内容的提问来源于stack exchange,提问作者Rick
相关产品推荐
相关产品推荐

