簡體   English   中英

從HTML字符串渲染React組件

[英]Rendering React components from an HTML string

我從AJAX請求中獲取HTML字符串,看起來像這樣:

<div> <SpecialComponent/> <SecondSpecialComponent/></div>

我需要的是能夠在React組件中使用此字符串,因為它是有效的JSX。

我嘗試按照此討論中的指示使用dangerouslySetInnerHTML SetInnerHTML: how-to-parse-html-to-react-component

我還嘗試了React庫,例如react-html-parsehtml-react-parser 沒有成功

當我使用AngularJS(1)時 ,我正在使用一些小指令來處理這種情況。 我需要用React實現相同的目的。 有任何想法嗎?

編輯:如果有人感興趣,我找到了一個可以解決該問題的庫: https : //www.npmjs.com/package/react-jsx-parser

您不應該以這種方式做事。 盡管使用JSX時React組件看起來像html標簽,但它們實際上是類或函數。 您要嘗試執行的操作等同於嘗試解析:

"<div>document.write('foo')</div>"

您實際上是將字符串形式的javascript函數名稱與html標記混合在同一字符串中。 您將必須解析字符串以將React組件與周圍的html標記分開,將字符串形式的React組件映射到其實際的React對應組件,並使用ReactDOM.render將組件添加到頁面。

let mapping = [
    {"name":"<SpecialComponent/><SecondSpecialComponent/>","component":<SpecialComponent/><SecondSpecialComponent/>},
    {"name":"<someOtherComponent/><someOtherComponent/>","component":<someOtherComponent/><someOtherComponent/>}
];
let markup = "<div><SpecialComponent/><SecondSpecialComponent/></div>";
let targetComponent;

mapping.forEach((obj) => {if(markup.indexOf(obj.name)>-1){
    targetComponent=obj.component;//acquired a reference to the actual component
    markup.replace(obj.name,"");//remove the component markup from the string
    }
});

/*place the empty div at the target location within the page 
give it an "id" attribute either using element.setAttribute("id","label") or 
by just modifying the string to add id="label" before the div is placed in 
the DOM ie, <div id='label'></div>*/

//finally add the component using the id assigned to it

ReactDOM.render(targetComponent,document.getElementById("label"));

以前從未嘗試過。 我想知道這是否真的有效:)

我的建議是您執行以下操作。

首先將狀態變量設置為等於要返回的HTML

this.setState({html: response.data.html})

然后您可以返回以下內容

   return ( 
   {this.state.html} 
   );

暫無
暫無

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

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