[英]How to render string including JSX component with PascalCase in React?
我有一個 React 應用程序,從外部 cms 接收博客文章數據。 數據是原始的 HTML 作為字符串,如下所示:
<h1>hello</h1>
<img src="example.com/felan.jpg">
<p>some text</p>
<img src"example.com/another.jpg">
...
現在,我想用一個名為Img
的 jsx 組件(大寫 I)替換img
HTML 標記。 我這樣做:
let postContentOptimized = post.replace("img", "Img");
<article dangerouslySetInnerHTML={{ __html: postContentOptimized }} />
但它會自動將Img
轉換為img
(更改 PascalCase)。
我也嘗試使用其他組件名稱,它會引發此錯誤:
React will try to recreate this component tree from scratch using the error boundary you provided, ErrorBoundary.
我找到了一個名為react-jsx-parser
。 它的文檔並不簡單,因此我第一次找到它時就跳過了它。 如果您像我一樣感到困惑,請執行以下操作:
<JsxParser components={{ components used in your string }} jsx={the string you want to parse} />
例子:
<JsxParser components={{ Img }} jsx="<Img src="hello.png /><p>hello</p>" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.