如何在没有html标记的情况下呈现React Quill的内容?

问题描述

我设法使羽毛笔正常工作,但是现在我想显示没有html标记的编辑器中的内容。我尝试使用react-render-html npm程序包,该程序以前工作正常,但现在不再维护,并给我一个错误

Could not find a declaration file for module 'react-render-html'. /path/to/module
implicitly has an 'any' type.
  Try `npm install @types/react-render-html` if it exists or add a new declaration (.d.ts) file containing `declare module 'react-render-html';

它也显示带有html标记。因此,我尝试使用react-html-parserhtmrhtml-to-react npm软件包,它完美地适用于单个元素,但不适用于多个元素。 所以我尝试使用console.log来查看我从后端收到的内容,这给了我

<p>&lt;h2&gt;Hello&lt;/h2&gt;&lt;p&gt;how are you ? &lt;/p&gt; &lt;h2&gt;Hello&lt;/h2&gt;&lt;p&gt;how are you ? &lt;/p&gt; &lt;h2&gt;Hello&lt;/h2&gt;&lt;p&gt;how are you ? &lt;/p&gt; &lt;h2&gt;Hello&lt;/h2&gt;&lt;p&gt;how are you ? &lt;/p&gt; &lt;h2&gt;Hello&lt;/h2&gt;&lt;p&gt;how are you ? &lt;/p&gt;

现在我想呈现不带有html标记代码,因此我再次执行console.log来查看是否通过执行正确转换了

  //import renderHtml from 'htmr';
  //import renderHtml from 'html-to-react';

    import renderHtml from 'react-html-parser';
 
  console.log(renderHtml(${blog.excerpt}))

最终它给了我

<h2>Hello</h2><p>how are you ? </p>
<h2>Hello</h2><p>how are you ? </p> 
<h2>Hello</h2><p>how are you ? </p> 
<h2>Hello</h2><p>how are you ? </p> 
<h2>Hello</h2><p>how are you ? </p>

我也尝试过dangerouslysetinnerhtml 但它不再起作用

解决方法

看您的服务器响应,HTML标记被转义。您需要先对其进行转义,然后再传递给HTML解析器。

您可以使用html-entities来解码服务器响应。最简单的方法是替换所有&lt;&gt;字符。

const decodedHtml = htmlEntities.decode(html)
// or
const decodedHtml = html.replace(/&lt;/g,'<').replace(/&gt;/g,'>')

return htmr(decodedHtml)