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

Next.js中dangerouslySetInnerHTML渲染HTML字符串显示异常问题

Next.js渲染HTML字符串显示样式异常的解决方案

你的问题核心是:HTML标签已被正确解析(元素检查可见),但视觉排版不符合预期,这大概率是CSS样式丢失或被重置导致的,以下是几种可行的解决办法:

1. 给渲染容器添加自定义样式恢复排版

Next.js的全局样式或第三方样式可能重置了<p>、<ul>、<li>等元素的默认样式(比如去掉列表缩进、段落间距)。给渲染HTML的容器加专属类,手动补充样式:

// 组件代码
const details = "<p>All confirmed bookings:</p><ul><li>Travelling up to&nbsp;<strong>31st August 2023</strong>&nbsp;will be charged the additional park fee at the property</li><li>Travelling between&nbsp;<strong>1st September 2023 - 15th October 2023</strong>&nbsp;will have the choice to be invoiced prior to travel or pay the additional park fee at the property</li><li>Travelling after&nbsp;<strong>15th October 2023</strong>&nbsp;onward will be invoiced</li></ul>"

return (
  <div className="rendered-html-content" dangerouslySetInnerHTML={{__html: details}} />
)

对应的CSS(可放在组件样式文件或全局样式中):

.rendered-html-content p {
  margin: 1em 0;
}
.rendered-html-content ul {
  padding-left: 1.5em;
  margin: 1em 0;
  list-style-type: disc;
}
.rendered-html-content li {
  margin: 0.3em 0;
}
.rendered-html-content strong {
  font-weight: 700;
}

2. 用Tailwind Typography插件快速解决富文本排版

如果你的项目使用Tailwind CSS,官方的@tailwindcss/typography插件可以一键恢复标准富文本样式:

  1. 安装插件:
npm install @tailwindcss/typography
  1. 在tailwind.config.js中启用插件:
module.exports = {
  theme: {
    // ...
  },
  plugins: [
    require('@tailwindcss/typography'),
    // ...
  ],
}
  1. 给渲染容器添加prose类:
<div className="prose" dangerouslySetInnerHTML={{__html: details}} />

3. 清理HTML字符串中的多余&nbsp;

字符串中大量的&nbsp;可能导致排版异常,尝试替换为普通空格后再渲染:

const cleanedDetails = details.replace(/&nbsp;/g, ' ');

return (
  <div dangerouslySetInnerHTML={{__html: cleanedDetails}} />
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:13:38