Next.js中Quill编辑器结合quill-blot-formatter2图片对齐功能失效问题排查求助
Next.js中Quill编辑器结合quill-blot-formatter2图片对齐功能失效问题排查求助
各位大佬好!我正在给我的Next.js项目集成富文本编辑器,选用了react-quill-new配合@enzedonline/quill-blot-formatter2来实现图片的缩放和对齐功能。目前图片缩放功能一切正常,但点击对齐按钮(左/中/右)的时候,图片完全没有任何位置变化。
我特意点开控制台检查了图片元素,发现点击对齐按钮后,图片上根本没有被添加上对应的对齐CSS类,样式文件里的规则是写了的,但就是没生效。实在卡在这里了,来求助大家帮忙看看哪里出问题了!
用到的技术栈
- Next.js(App Router,使用"use client"指令)
- react-quill-new
- @enzedonline/quill-blot-formatter2
- 自定义Image Blot组件
- quill-image-drop-module
关键代码片段
1. 编辑器模块配置(page.ts中核心配置)
const modules = useMemo( () => ({ toolbar: { container: [ [{ header: [1, 2, 3, false] }], ["bold", "italic", "underline", "strike", "blockquote"], [{ list: "ordered" }, { list: "bullet" }], [{ color: [] }, { background: [] }], [{ indent: "-1" }, { indent: "+1" }], [{ align: [] }], ["link", "image"], ["clean"], ], handlers: { image: imageHandler }, }, history: { delay: 1000, maxStack: 100, userOnly: false, }, imageDrop: true, blotFormatter2: { align: { allowAligning: true, alignments: ["left", "center", "right"], }, resize: { allowResizing: true }, image: { allowAltTitleEdit: true, allowLinkEdit: false }, }, }), [imageRadius] );
2. 自定义Image Blot组件(CustomImage.ts)
import Quill from 'quill'; interface EmbedConstructor { new (): any; create: (value: any) => HTMLElement; value?: (node: HTMLElement) => any; } const QuillBlockEmbed = Quill.import('blots/block/embed') as unknown; const BlockEmbed = QuillBlockEmbed as EmbedConstructor; class CustomImage extends (BlockEmbed as any) { static blotName = 'image'; static tagName = 'img'; static create(value: any) { const node = (super.create as (value: any) => HTMLElement)(value); if (typeof value === 'string') { node.setAttribute('src', value); } else { Object.keys(value).forEach((key) => { node.setAttribute(key, value[key]); }); } return node; } static value(node: HTMLElement) { const attributes: Record<string, string> = {}; const attrs = Array.from(node.attributes) as Attr[]; attrs.forEach((attr) => { attributes[attr.name] = attr.value; }); return attributes; } } export default CustomImage;
3. 对齐样式文件(styles.css)
/* Image alignment */ .ql-align-center img, img.ql-align-center { display: block; margin-left: auto; margin-right: auto; } .ql-align-right img, img.ql-align-right { display: block; margin-left: auto; margin-right: 0; } .ql-align-left img, img.ql-align-left { display: block; margin-left: 0; margin-right: auto; }
我已经排查的内容
- 点击对齐按钮后控制台没有任何报错信息
- 检查图片元素,确认点击后未被添加上
ql-align-left/ql-align-center/ql-align-right这类对齐类名 - 手动给图片添加对齐类名时,样式能正常生效,说明样式文件本身没问题
- 怀疑过自定义Image Blot的影响,但看代码只是继承了BlockEmbed并处理了属性,没动对齐相关逻辑
有没有大佬遇到过类似的问题?或者能帮我看看是不是quill-blot-formatter2的配置、自定义Blot的注册哪里有疏漏?麻烦各位了!
内容来源于stack exchange
相关产品推荐
相关产品推荐

