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

求助:使用dangerouslySetInnerHTML渲染Sun Editor生成的HTML样式不生效

解决SunEditor生成HTML通过dangerouslySetInnerHTML渲染时样式不生效的问题

问题原因

SunEditor的suneditor.min.css样式是基于编辑器组件的特定容器类名编写的(比如.sun-editor、.sun-editor-editable这类父级类),直接用dangerouslySetInnerHTML渲染生成的HTML时,缺少这些外层容器类,导致CSS选择器无法匹配到内部的文本元素(比如<p>、<h1>、<ul>等),自然样式就不生效。而<SunEditor/>组件本身会自动给内容包裹这些容器类,所以样式能正常应用。

解决步骤

  1. 给渲染容器添加SunEditor的内容区域类名
    给包裹dangerouslySetInnerHTML的div加上sun-editor-editable类,让内部HTML元素能匹配到CSS中的选择器:

    import { useLocation } from "react-router-dom"
    import { blogDetailsType } from "./BlogForm"
    import DOMPurify from "dompurify";
    import 'suneditor/dist/css/suneditor.min.css'; 
    
    const Preview = () => {
        const location = useLocation()
        const data: blogDetailsType = location?.state
        const sanitizedHtml = DOMPurify.sanitize(data?.blog_html);
        
        return (
            <div className="tw:text-primary text-responsive-sm tw:py-4">
                    {/* 添加sun-editor-editable类 */}
                    <div className="sun-editor-editable" dangerouslySetInnerHTML={{__html:sanitizedHtml}}></div>
            </div>
        )
    }
    
    export default Preview
    
  2. 确保DOMPurify没有过滤必要的类名
    如果SunEditor生成的HTML里自带了编辑器相关的类(比如.se-paragraph),需要配置DOMPurify允许这些类,避免被过滤:

    const sanitizedHtml = DOMPurify.sanitize(data?.blog_html, {
        ADD_CLASS_NAMES: ['se-paragraph', 'se-heading', 'se-list-item'] // 根据实际生成的类名添加
    });
    
  3. 验证CSS引入是否生效
    可以在浏览器开发者工具中检查suneditor.min.css是否成功加载,并且查看渲染后的元素是否能匹配到对应的CSS规则(比如查看<p>元素的样式是否被.sun-editor-editable p这类选择器覆盖)。

内容的提问来源于stack exchange,提问作者Richard David

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 15:42:03