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

如何在react-draft-wysiwyg编辑器中添加额外自定义font family?

react-draft-wysiwyg 自定义字体族配置方案

结论

可以正常添加自定义字体族,react-draft-wysiwyg 的 fontFamily 工具栏配置原生支持扩展自定义字体,你当前使用的依赖版本完全兼容该特性,无需额外调整依赖版本。

实现步骤

1. 调整工具栏配置

直接将你需要新增的字体名称追加到 fontFamily 的 options 数组即可,示例代码如下:

import { Editor } from 'react-draft-wysiwyg';
import 'react-draft-wysiwyg/dist/react-draft-wysiwyg.css';

const toolbarConfig = {
  // 其他原有工具栏配置保留
  fontFamily: {
    options: [
      'Arial',
      'Georgia',
      'Impact',
      'Tahoma',
      'Times New Roman',
      'Verdana',
      // 以下为新增的自定义字体,可根据需求自行增减
      'PingFang SC',
      'Microsoft YaHei',
      'MyCustomFont'
    ]
  }
};

// 编辑器组件调用示例
const MyEditor = () => {
  return (
    <Editor
      toolbar={toolbarConfig}
      // 其他原有编辑器配置保留
    />
  );
};

注意:你原有配置中的 Times new Roman verdena 存在语法错误,需用逗号分隔两个字体名称,否则会被识别为同一个字体导致渲染异常。

2. 补充字体样式配置

需要额外添加CSS样式,保证工具栏字体选项和编辑器内容能正确渲染对应字体,如果你使用的是自定义的外部字体文件,需要先通过@font-face引入:

/* 仅使用系统内置字体可跳过该部分,自定义外部字体需先引入 */
@font-face {
  font-family: 'MyCustomFont';
  src: url('./static/fonts/MyCustomFont.woff2') format('woff2'),
       url('./static/fonts/MyCustomFont.woff') format('woff');
  font-weight: normal;
  font-style: normal;
}

/* 工具栏下拉选项用对应字体显示,优化用户选择体验 */
.rdw-fontfamily-optionwrapper span[data-value="PingFang SC"] {
  font-family: 'PingFang SC', sans-serif;
}
.rdw-fontfamily-optionwrapper span[data-value="Microsoft YaHei"] {
  font-family: 'Microsoft YaHei', sans-serif;
}
.rdw-fontfamily-optionwrapper span[data-value="MyCustomFont"] {
  font-family: 'MyCustomFont', sans-serif;
}

/* 编辑器内容区域渲染对应字体 */
.public-DraftStyleDefault-block [style*="font-family: PingFang SC"] {
  font-family: 'PingFang SC', sans-serif !important;
}
.public-DraftStyleDefault-block [style*="font-family: Microsoft YaHei"] {
  font-family: 'Microsoft YaHei', sans-serif !important;
}
.public-DraftStyleDefault-block [style*="font-family: MyCustomFont"] {
  font-family: 'MyCustomFont', sans-serif !important;
}

注意事项

  • options 数组中的字体名称需要和 CSS 中定义的 font-family 完全一致,大小写敏感,否则会出现样式匹配失败的问题
  • 如果需要将编辑器输出的HTML内容渲染到其他页面,对应页面也需要引入相同的字体样式配置,否则自定义字体无法正常显示
  • 低版本浏览器下部分小众字体可能存在兼容问题,建议配置 fallback 通用字体族(比如 sans-serif、serif)避免字体失效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 22:27:04