【问题标题】:How to render the content of React Quill without the html markup?如何在没有 html 标记的情况下呈现 React Quill 的内容?
【发布时间】:2020-12-02 23:42:57
【问题描述】:

我设法让我的 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 packages,它适用于单个元素,但不适用于多个元素。 所以我尝试使用 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 但它不再工作了

【问题讨论】:

    标签: javascript html node.js reactjs react-quill


    【解决方案1】:

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

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

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

    【讨论】:

    • 我还有一个问题,当我尝试传递 html 代码 import dynamic from 'next/dynamic'; const ReactQuill = dynamic( ()=&gt; import('react-quill'), {ssr:false} ) import '../../node_modules/react-quill/dist/quill.snow.css' const ReactQuillEditor = () =&gt;{ &lt;ReactQuill placeholder="Write here, minimum of 200 charaters is required" modules={CreateBlog.modules} formats={ CreateBlog.formats } &gt; &lt;/ReactQuill&gt; } 它给了我一个全新的错误,有什么办法可以解决它?
    • 只有当我将任何代码块从编辑器发送到数据库并尝试显示内容时才会发生这种情况
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-21
    • 2012-04-09
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    • 2015-04-27
    • 1970-01-01
    相关资源
    最近更新 更多