簡體   English   中英

如何在沒有 html 標記的情況下呈現 React Quill 的內容?

[英]How to render the content of React Quill without the html markup?

我設法讓我的 Quill 工作,但現在我想顯示編輯器中沒有 html 標記的內容。 我嘗試使用react-render-html npm package,它之前工作正常但現在不再維護並給我一個錯誤

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)

要解決這個問題,只需粘貼一行<div dangerouslySetInnerHTML={{ __html:value }} />

這里的值是你從 react-quill 得到的 HTML。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM