You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React/Next.js集成TinyMCE编辑器遇TypeError问题求助

修复TinyMCE集成时的"TypeError: editor1 is null"错误

你的问题出在两个关键地方:

  • 在handleSubmit函数内部重新声明了editor变量,直接覆盖了外部用来存储编辑器实例的变量,导致调用editor.getContent()时拿到的是你刚声明的null值
  • 没有用React的useRef来持久化编辑器实例,函数组件中普通变量会在每次渲染时重置,无法保留编辑器的引用

修复步骤:

  1. 导入React的useRef钩子
  2. 用useRef创建一个持久化的引用存储编辑器实例
  3. 修改onInit回调,将编辑器实例赋值给ref的current属性
  4. 在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 16:25:22