React Jodit Editor onChange失焦及useMemo使用异常问题求助
解决Jodit编辑器在React中失去焦点/光标跳转问题
问题根源
- 使用组件自带的
onChange时,每次内容变更触发state更新,导致组件重渲染,Jodit编辑器实例被重置,进而出现光标跳转或失去焦点。 - 单独将
config放入useMemo无法彻底解决,因为state更新引发的重渲染仍会影响编辑器的光标状态。
解决方案1:通过编辑器Ref监听原生Change事件(推荐)
直接借助编辑器Ref监听Jodit原生change事件,绕过组件onChange引发的重渲染问题,同时实时获取HTML内容:
// 在组件中添加useEffect监听编辑器事件 useEffect(() => { if (editor.current) { const handleEditorChange = (newContent) => { updateArticle({ type: 'field', field: 'content', value: newContent }) } // 绑定原生change事件 editor.current.events.on('change', handleEditorChange) // 组件卸载时移除监听,避免内存泄漏 return () => { editor.current.events.off('change', handleEditorChange) } } }, []) // 移除JoditEditor组件的onChange属性 <JoditEditor id='article-content' ref={editor} value={article.content} config={config} tabIndex={1} />
解决方案2:优化组件渲染逻辑(兼容原有onChange写法)
如果坚持使用组件的onChange,可以通过React.memo减少编辑器不必要的重渲染,并添加内容判重避免无效state更新:
import React from 'react' // 封装Memo化的JoditEditor,仅在value或config变化时重渲染 const MemoizedJoditEditor = React.memo(JoditEditor, (prevProps, nextProps) => { return prevProps.value === nextProps.value && prevProps.config === nextProps.config }) // 渲染时使用MemoizedJoditEditor,并添加内容判重 <MemoizedJoditEditor id='article-content' ref={editor} value={article.content} config={config} tabIndex={1} onChange={(newContent) => { // 仅当内容真正变化时更新state if (newContent !== article.content) { updateArticle({ type: 'field', field: 'content', value: newContent }) } }} />
关键注意事项
- 禁止用
useMemo包裹整个组件的返回值,这会导致表单输入框无法响应state变化(useMemo会缓存渲染结果,依赖项不变时不会更新)。 - 确保
loadArticle加载文章时,content字段被正确赋值,避免编辑器初始渲染异常。
内容的提问来源于stack exchange,提问作者Vanortton
相关产品推荐
相关产品推荐

