ReactQuill模块处理器传递带参数函数时出现运行时错误
解决ReactQuill配置工具栏处理器时传递带参数函数的报错问题
问题场景
配置ReactQuill的工具栏处理器时,尝试传递带quillRef参数的函数,实现代码如下:
处理器配置代码
getModules = (quillRef) => ({ toolbar: { container: toolbarOptions, handlers: { link: () => this.openLinkDialog(quillRef), }, }, });
编辑器渲染代码
renderEditor = (quillRef, onChangeHandler) => { const modules = this.getModules(quillRef); return ( <div> <ReactQuill ref={quillRef} modules={modules} onChange={onChangeHandler} /> </div> ); };
运行时出现以下错误:
Uncaught runtime errors: × ERROR Cannot read properties of undefined (reading 'delta') TypeError: Cannot read properties of undefined (reading 'delta') at ReactQuill.componentDidUpdate (http://localhost:3000/static/js/bundle.js:178758:20) at commitLayoutEffectOnFiber
问题原因
每次调用getModules都会生成全新的modules对象(包括内部的toolbar和handlers对象),导致ReactQuill组件每次渲染时都检测到modules属性发生变化,触发不必要的重新初始化,进而在componentDidUpdate阶段出现内部状态异常(delta为undefined)。
解决方案
方案1:缓存modules对象,避免重复生成
在类组件中,可以将modules缓存到实例属性中,仅在必要时重新生成:
// 组件初始化时声明缓存变量 this.cachedModules = null; getModules = (quillRef) => { if (!this.cachedModules) { this.cachedModules = { toolbar: { container: toolbarOptions, handlers: { link: () => this.openLinkDialog(quillRef), }, }, }; } return this.cachedModules; };
如果是函数组件,使用useMemo进行缓存:
const modules = useMemo(() => ({ toolbar: { container: toolbarOptions, handlers: { link: () => openLinkDialog(quillRef), }, }, }), [quillRef]); // 仅当quillRef变化时重新生成modules
方案2:直接利用处理器默认参数获取Quill实例
Quill工具栏的处理器函数默认会接收当前Quill实例作为第一个参数,无需手动传递quillRef,这样可以简化代码并保证modules对象的稳定性:
getModules = () => ({ toolbar: { container: toolbarOptions, handlers: { link: (quillInstance) => this.openLinkDialog(quillInstance), }, }, });
此时getModules无需接收参数,返回的modules对象引用稳定,不会触发ReactQuill的不必要重渲染。
内容的提问来源于stack exchange,提问作者jack mama
相关产品推荐
相关产品推荐

