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

React项目中sanitize-html无法允许react-quill生成的<br>标签问题

问题分析

问题出在sanitize-html的空标签默认处理逻辑:即便你将br加入allowedTags,它仍会移除空标签(包括自闭合的br),除非你明确配置允许保留这类标签。


解决方案

修改sanitize-html的配置,同时设置allowedTags和allowedEmptyTags,确保br标签被保留:

const extension = (joi) => ({
  type: 'string',
  base: joi.string(),
  messages: {
    'string.escapeHTML': '{{#label}} must not include HTML tags',
  },
  rules: {
    escapeHTML: {
      validate(value, helpers) {
        const clean = sanitizeHtml(value, {
          allowedClasses: {
            '*': [
              'ql-align-right',
              'ql-align-center',
              'ql-align-justify',
              'ql-code-block',
              'ql-code-block-container',
              'ql-syntax',
              'ql-direction-rtl',
              'ql-font-serif',
              'ql-font-monospace',
              'ql-formula',
              'ql-indent-1',
              'ql-indent-2',
              'ql-indent-3',
              'ql-indent-4',
              'ql-indent-5',
              'ql-indent-6',
              'ql-indent-7',
              'ql-indent-8',
              'ql-size-small',
              'ql-size-large',
              'ql-size-huge',
            ],
          },
          // 确保br在允许的标签列表中
          allowedTags: [...sanitizeHtml.defaults.allowedTags, 'br'],
          // 显式允许br作为空标签保留(默认已包含,但声明后更稳妥)
          allowedEmptyTags: [...sanitizeHtml.defaults.allowedEmptyTags, 'br'],
          // 可选:保留仅包含br的p标签
          preserveEmptyTags: true,
        });
        if (clean !== value)
          return helpers.error('string.escapeHTML', { value });
        return clean;
      },
    },
  },
});

特殊场景处理

如果尝试过allowedTags: false和allowedAttributes: false仍无效,只需添加allowedEmptyTags: false禁用空标签移除逻辑即可:

const clean = sanitizeHtml(value, {
  allowedTags: false,
  allowedAttributes: false,
  allowedEmptyTags: false,
});

原理说明

sanitize-html默认会移除所有空标签(包括自闭合的br),只有标签在allowedEmptyTags列表中时才会被保留。自定义allowedTags时,需同时确保br被包含在内,再通过allowedEmptyTags或preserveEmptyTags配置避免其被清理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 03:43:18