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 <strong>31st August 2023</strong> will be charged the additional park fee at the property</li><li>Travelling between <strong>1st September 2023 - 15th October 2023</strong> will have the choice to be invoiced prior to travel or pay the additional park fee at the property</li><li>Travelling after <strong>15th October 2023</strong> 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插件可以一键恢复标准富文本样式:
- 安装插件:
npm install @tailwindcss/typography
- 在
tailwind.config.js中启用插件:
module.exports = { theme: { // ... }, plugins: [ require('@tailwindcss/typography'), // ... ], }
- 给渲染容器添加
prose类:
<div className="prose" dangerouslySetInnerHTML={{__html: details}} />
3. 清理HTML字符串中的多余
字符串中大量的 可能导致排版异常,尝试替换为普通空格后再渲染:
const cleanedDetails = details.replace(/ /g, ' '); return ( <div dangerouslySetInnerHTML={{__html: cleanedDetails}} /> )
内容的提问来源于stack exchange,提问作者Gelo Chang
相关产品推荐
相关产品推荐

