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

React Quill如何实现同一行文本部分左对齐部分右对齐

实现React Quill内同一行文本左右分栏对齐

核心问题原因

React Quill基于Quill.js,默认的HTML清理规则会过滤非标准样式属性,且内置对齐格式仅作用于块级元素,直接写入带flex样式的<p>标签会被编辑器重新解析为普通段落,导致样式失效。

解决方案步骤

1. 扩展Quill的HTML白名单,放开样式限制

Quill默认限制了块级元素的属性,需修改配置允许<p>标签携带style属性:

import Quill from 'quill';

// 获取默认块级元素配置
const Parchment = Quill.import('parchment');
const defaultBlock = Parchment.query('block');
defaultBlock.tagName = 'P';
// 移除默认对style属性的过滤
delete defaultBlock.attributes.style;
defaultBlock.whitelist.style = true;

// 重新注册块级元素规则
Quill.register(defaultBlock, true);

2. 自定义工具栏按钮与格式切换逻辑

在工具栏中添加自定义的"左右分栏"按钮,实现点击时切换段落的flex样式:

import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';

const modules = {
  toolbar: {
    container: [
      ['bold', 'italic', 'underline'],
      [{ header: [1, 2, 3, false] }],
      ['splitAlign'] // 添加自定义按钮
    ],
    handlers: {
      splitAlign: function() {
        const range = this.quill.getSelection();
        if (!range) return;
        
        // 获取当前选中的段落块
        const block = this.quill.getLine(range.index)[0];
        if (block) {
          const currentDisplay = block.domNode.style.display;
          // 切换flex样式状态
          if (currentDisplay === 'flex') {
            block.domNode.style.display = '';
            block.domNode.style.justifyContent = '';
          } else {
            block.domNode.style.display = 'flex';
            block.domNode.style.justifyContent = 'space-between';
            // 空段落自动插入占位文本
            if (block.domNode.textContent.trim() === '') {
              this.quill.insertText(range.index, '左栏内容');
              this.quill.insertText(range.index + 5, '右栏内容');
              this.quill.setSelection(range.index + 5, 0);
            }
          }
        }
      }
    }
  }
};

// 自定义按钮样式(可选)
const toolbarStyle = `
  .ql-splitAlign::before {
    content: '←→';
    font-size: 16px;
  }
`;

3. 在组件中使用配置好的编辑器

import { useState, useEffect } from 'react';

function SplitAlignEditor() {
  const [content, setContent] = useState('');
  
  // 初始化时设置示例分栏内容
  useEffect(() => {
    setContent(`<p style="display:flex;justify-content:space-between"><span>左对齐文本</span><span>右对齐文本</span></p>`);
  }, []);
  
  return (
    <>
      <style>{toolbarStyle}</style>
      <ReactQuill
        theme="snow"
        value={content}
        onChange={setContent}
        modules={modules}
      />
    </>
  );
}

4. 内容的保存与渲染

保存时直接存储编辑器输出的HTML即可;外部展示时直接解析HTML,编辑器内重新加载时,由于已配置白名单,flex样式会被正确识别渲染。

注意事项

  • 不要尝试在段落内嵌套其他块级元素(如另一个<p>),Quill会自动拆分这类非法嵌套结构
  • 如果需要支持更复杂的分栏场景,可自定义Blot模块创建专属的分栏容器,比直接操作style更稳定

内容的提问来源于stack exchange,提问作者Guilherme do Valle

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:50:10