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

React Draft Wysiwyg 如何替换默认工具栏图标为自定义图标(如React Icons)

React Draft Wysiwyg 工具栏自定义图标解决方案

核心原因:react-draft-wysiwyg 的工具栏 icon 配置项仅接收字符串格式的HTML内容,不支持直接传入React组件或JSX元素,因此你之前的写法无法生效,可通过以下几种方案实现自定义:

方案1:将React Icons组件转为HTML字符串传入

使用 react-dom/server 提供的渲染方法将图标组件转为HTML字符串,直接赋值给icon属性即可:

import { AiOutlineUnorderedList } from 'react-icons/ai'
// 导入服务端渲染工具
import { renderToStaticMarkup } from 'react-dom/server'

export const toolbarOptions = {
  options: ['list', 'link'],
  list: {
    options: ['unordered', 'ordered'],
    unordered: {
      // 将组件转为HTML字符串
      icon: renderToStaticMarkup(<AiOutlineUnorderedList />),
      className: undefined,
    },
  },
  link: {
    options: ['link'],
  },
}

注:React 18环境下该方法依然可用,也可以替换为renderToString,效果一致

方案2:自定义图片/SVG直接传入HTML字符串

如果要使用本地SVG或者图片,直接将HTML代码作为字符串传入即可:

unordered: {
  // 直接传入img标签的HTML字符串
  icon: `<img src="./path-to-svg" alt="无序列表" width="16" height="16" />`,
  className: undefined,
}

方案3:CSS样式覆盖(无需修改配置逻辑)

你也可以通过自定义类名加CSS样式的方式替换图标,不需要处理HTML字符串:

  1. 给对应按钮配置自定义类名
unordered: {
  icon: undefined,
  className: 'custom-unordered-icon',
}
  1. 编写CSS样式替换默认图标
/* 隐藏默认图标 */
.custom-unordered-icon .rdw-list-unordered-icon {
  display: none;
}
/* 插入自定义图标 */
.custom-unordered-icon .rdw-option-wrapper::before {
  content: '';
  display: inline-block;
  width: 16px;
  height: 16px;
  background: url('./path-to-your-icon') no-repeat center / contain;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 04:45:04