簡體   English   中英

如何在 React 中使用 PascalCase 渲染包含 JSX 組件的字符串?

[英]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.

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