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

如何给react-reader npm包添加自定义fontFamily

react-reader 自定义font-family 解决方案

react-reader 渲染的 epub 内容是独立在 iframe 沙箱内的,外层 CSS 无法直接作用到 iframe 内的文档节点,需要通过 epubjs 提供的钩子注入样式实现自定义字体配置,具体操作步骤如下:

  • 第一步:在项目全局样式中先声明自定义字体的@font-face规则,确保字体资源可正常访问
/* 全局CSS文件,比如index.css */
@font-face {
  font-family: "MyCustomFont";
  src: url("./assets/fonts/MyCustomFont.woff2") format("woff2");
  font-weight: normal;
  font-style: normal;
}
  • 第二步:通过ReactReader组件的getRendition属性获取渲染实例,在内容加载完成后注入自定义字体样式
import React, { useRef } from 'react';
import { ReactReader } from 'react-reader';

const EpubReader = () => {
  const renditionRef = useRef(null);

  const handleRendition = (rendition) => {
    renditionRef.current = rendition;
    // 监听内容渲染完成事件
    rendition.on('rendered', () => {
      // 方式1:通过主题配置覆盖样式
      rendition.themes.default({
        '*': {
          'font-family': 'MyCustomFont, sans-serif !important'
        }
      });
      // 方式2:直接注入完整CSS字符串(方式1不生效时使用)
      // rendition.themes.inject(`
      //   * {
      //     font-family: 'MyCustomFont', sans-serif !important;
      //   }
      // `)
    });
  };

  return (
    <div style={{ height: '100vh' }}>
      <ReactReader
        url="/你的电子书文件路径.epub"
        getRendition={handleRendition}
      />
    </div>
  );
};

export default EpubReader;
  • 异常排查
    • 字体不生效先检查字体资源路径是否正确,存放在public目录的资源引用不要加相对路径前缀
    • 部分epub文件自带内联font-family样式,必须加!important提升样式优先级才能覆盖
    • 样式注入必须在rendered事件触发后执行,执行时机过早会因为iframe内容未加载完成导致样式失效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 20:30:04