React/Next.js中如何在handleSubmit内获取编辑器变量值
解决React/Next.js中获取TinyMCE编辑器内容并在提交时弹窗显示的问题
你可以通过两种方式实现需求,直接且高效:
方法一:提交时直接从编辑器实例获取内容
你已经将编辑器实例存在了editor状态中,无需在useEffect里提前缓存内容,直接在提交函数里调用实例的getContent()方法即可:
import { useState } from 'react'; import Editor from '@tinymce/tinymce-react'; const YourComponent = () => { // 给状态加上类型,避免any(如果有TinyMCE类型定义的话,可用EditorInstance替代any) const [editor, setEditor] = useState<any>(null); const handleSubmit = async(e: React.FormEvent) => { e.preventDefault(); // 先判断编辑器实例是否已初始化,避免报错 if (editor) { const content = editor.getContent(); alert('content is ' + content); } } return ( <form onSubmit={handleSubmit}> <Editor onInit={(evt, ed) => setEditor(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;
这种方式的优势是不需要额外维护内容状态,每次提交时直接拉取编辑器的最新内容,适合仅在提交时需要内容的场景。
方法二:实时同步内容到状态(适合实时预览等场景)
如果需要实时获取编辑器内容(比如做实时预览),可以新增一个content状态,通过编辑器的onChange事件实时更新:
import { useState } from 'react'; import Editor from '@tinymce/tinymce-react'; const YourComponent = () => { const [editor, setEditor] = useState<any>(null); // 初始化值和编辑器初始内容保持一致 const [content, setContent] = useState<string>("<p>This is the initial content of the editor.</p>"); const handleSubmit = async(e: React.FormEvent) => { e.preventDefault(); alert('content is ' + content); } return ( <form onSubmit={handleSubmit}> <Editor onInit={(evt, ed) => setEditor(ed)} initialValue={content} // 实时同步编辑器内容到状态 onChange={(evt) => setContent(evt.target.getContent())} 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;
注意事项
- 尽量给状态加上明确的类型,避免
any(可安装@types/tinymce获取官方类型定义) - 提交时判断编辑器实例是否存在,防止组件初始化完成前点击提交导致报错
内容的提问来源于stack exchange,提问作者Rick
相关产品推荐
相关产品推荐

