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

如何在TypeScript环境下为React Quill工具栏添加颜色选择器

在React+TypeScript项目中为react-quill添加颜色选择器

要给react-quill的工具栏添加颜色和背景色选择器,只需两步修改你的代码:

1. 更新工具栏配置

在modules.toolbar数组中新增颜色和背景色的配置项,空数组会使用Quill默认的颜色面板,也可以传入自定义颜色值:

const modules = {
  toolbar: [
    [{ font: ['', 'times-new-roman', 'arial'] }],
    [{ header: [1, 2, 3, false] }],
    ['bold', 'italic', 'underline', 'strike', 'blockquote'],
    [{ list: 'ordered' }, { list: 'bullet' }, { indent: '-1' }, { indent: '+1' }],
    [{ color: [] }, { background: [] }], // 新增颜色选择器(默认面板)
    // 若要自定义颜色,可改为:[{ color: ['#000', '#ff0000', '#00ff00', '#0000ff'] }, { background: ['#ffffcc'] }]
    ['link'],
    ['clean']
  ],
};

2. 更新格式列表

react-quill需要明确指定启用的格式,所以要在formats数组中添加color和background:

const formats = [
  'font',
  'header',
  'bold',
  'italic',
  'underline',
  'strike',
  'blockquote',
  'list',
  'bullet',
  'indent',
  'link',
  'color', // 新增颜色格式
  'background', // 新增背景色格式
];

完整组件代码

import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css'; // 务必导入样式文件

const modules = {
  toolbar: [
    [{ font: ['', 'times-new-roman', 'arial'] }],
    [{ header: [1, 2, 3, false] }],
    ['bold', 'italic', 'underline', 'strike', 'blockquote'],
    [{ list: 'ordered' }, { list: 'bullet' }, { indent: '-1' }, { indent: '+1' }],
    [{ color: [] }, { background: [] }],
    ['link'],
    ['clean']
  ],
};

const formats = [
  'font',
  'header',
  'bold',
  'italic',
  'underline',
  'strike',
  'blockquote',
  'list',
  'bullet',
  'indent',
  'link',
  'color',
  'background',
];

function RichTextEditor() {
  return <ReactQuill theme="snow" modules={modules} formats={formats} preserveWhitespace />;
}

export default RichTextEditor;

注意:v2.x及以上版本的react-quill均支持这些格式,若遇到TypeScript类型报错,可安装@types/quill来获得完整的类型支持。

内容的提问来源于stack exchange,提问作者fatemeh zamanipour

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 12:27:50