React/Next.js中获取Editor值报错:TypeError: editor is null
React/Next.js获取Editor组件值时报错"TypeError: editor is null"的问题与修复
问题根源
- 事件函数内渲染组件完全无效:你在
handleSubmit里写的<Editor>代码根本不会被React挂载到页面,onInit回调永远不会触发,editor变量一直是null。 - 实例存储逻辑错误:用局部变量存编辑器实例,不仅无法跨组件渲染周期保留,还和页面上真正显示的Editor组件没有任何关联。
- 页面的Editor未绑定实例捕获:return里的
<Editor>没有配置onInit,完全没去获取编辑器实例。
修复后的完整代码
import { useRef } from 'react'; import { Editor } from '@tinymce/tinymce-react'; // 确认导入正确的Editor组件 const YourPageComponent = () => { // 用useRef存储编辑器实例,跨渲染周期保留引用 const editorRef = useRef<any>(null); const handleSubmit = async(e: React.FormEvent) => { e.preventDefault(); // 先判断实例是否存在,再调用方法 if (editorRef.current) { const content = editorRef.current.getContent(); alert('content is ' + content); } }; return ( <> <form className="forms-sample" onSubmit={handleSubmit}> <Editor onInit={(evt, ed) => { editorRef.current = ed; // 把实例存入ref }} 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" className='btn btn-primary mr-2'>Submit</button> </form> </> ); }; export default YourPageComponent;
核心修复说明
- 改用
useRef存储编辑器实例:React的useRef可以在组件整个生命周期内保留引用,不会因为组件重渲染丢失值。 - 把
onInit绑定到正确的Editor组件:页面上实际渲染的Editor才会触发onInit,把实例存入ref。 - 添加空值判断:调用
getContent前先检查editorRef.current是否存在,避免再次出现null报错。
内容的提问来源于stack exchange,提问作者user823 user
相关产品推荐
相关产品推荐

