代码之家  ›  专栏  ›  技术社区  ›  Joseph

在React中解析页面中的HTML

  •  -3
  • Joseph  · 技术社区  · 9 月前

    我很困惑,因为很明显,在我的React应用程序中,HTML没有被格式化为可读文本。我已经放置 dangerouslySetInnerHTM 但它不起作用。 我错过了什么?

    Codesandbox: CLICK HERE

    代码

    <div dangerouslySetInnerHTML={{ __html: message }} />
    
    1 回复  |  直到 9 月前
        1
  •  1
  •   0stone0    9 月前
    1. [[[a href=https://cal.com/deliciousdelights/flavorfusion-demo]]]
      这不是有效的HTML,因此React不会解析它。 您可以使用一些regex/replace magic来解决这个问题,但您最好从源代码处解决这个问题。

    2. 这个 /n 实际上已经转换,但由于某些CSS不是您所期望的“换行符”,请将以下CSS添加到 div :

      white-space: pre-wrap;
      

    演示显示上述更改

    const Example = () => {
    
        const message = `\nDear Alex Adriano,\n\nI hope this message finds you well. My name is Aung Kyaw, and I am the Business Development Associate at Delicious Delights, a leading food delivery service. I am reaching out to you today to introduce FlavorFusion, our curated meal delivery service designed to cater to the culinary needs of small and medium-sized enterprises (SMEs) like those you serve at Pacific Bank.\n\nAs an Account Officer at Pacific Bank, I understand that you work closely with SME clients who often face challenges in providing nutritious and convenient meal options for their teams. Many of these businesses struggle with time constraints and sourcing quality meals for their employees. This is where FlavorFusion can make a significant difference.\n\nFlavorFusion offers a diverse menu of freshly prepared, nutritious meals delivered directly to your clients' offices. Our service is designed to promote productivity and well-being among employees, offering convenient meal solutions that align with dietary preferences and health goals.\n\nI would welcome the opportunity to discuss how FlavorFusion can benefit your SME customers and provide a personalized demonstration of our service offerings. [[[a href=https://cal.com/deliciousdelights/flavorfusion-demo]]]Please let me know if you have time for a brief call to explore how we can work together to support the well-being and satisfaction of your SME clients' teams.[[[/a]]]\n\nThank you for your time, and I look forward to connecting with you.\n\nBest regards,\nAung Kyaw\nBusiness Development Associate\nDelicious Delights\[email protected]\n`;
    
    
        return (
            <div>
                <h1>{'Example'}</h1>
                <div dangerouslySetInnerHTML={{ __html: message }} />
            </div>
        )
    }
    ReactDOM.render(<Example />, document.getElementById("react"));
    div {
      white-space: pre-wrap;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script>
    <div id="react"></div>