2017-06-16 173 views
1

我有一個字符串,它實際上是一個嵌套的反應組件名稱及其道具。想要在另一個反應組件內渲染該字符串。 例如在React組件中轉換字符串

var String = "<parentComponent title='Parent'><childComponent age='23'></childComponent></parentComponent>" 

陣營代碼: -

class MainComponnet extends Component{ 
render(){ 
    let stringComponents = "<parentComponent title='Parent'><childComponent age='23'></childComponent></parentComponent>"; 
    return(
    {stringComponents} 
) 
} 
} 

父組件JSX: -

class ParentComponent extends Component{ 
render(){ 
    return(
    <div> {this.props.title}</div> 
) 
} 
} 

輔元件JSX: -

class ChildComponent extends Component{ 
render(){ 
    return(
    <div> {this.props.age}</div> 
) 
} 
} 

請幫助..

+0

一個問題,爲什麼它在一個字符串內? – VivekN

+0

其實服務將返回組件字符串,因此我必須呈現該組件。 – Kracki

+0

我認爲這樣做有些不可能。可能你需要一個react-jsx-parser來將字符串轉換爲正常的組件類型,然後渲染它 – VivekN

回答

0

該字符串具有JSX內容,您可以直接呈現JSX內容,組件名稱也必須以大寫字母開頭。

看到這個答案:React - Adding component after AJAX to view

class MainComponnet extends Component{ 
render(){ 
    let stringComponents = <ParentComponent title='Parent'><ChildComponent age='23'></ChildComponent></ParentComponent>; 
    return(
    </div>{stringComponents}</div> 
) 
} 
} 

如果你不能使用直接JSX元素,你可以使用通天改變你的字符串JSX。但它不是一個好主意。你應該修改你的邏輯。

的很多,每一個對我的幫助如下

import babel from 'babel-core'; 
var Component = eval(babel.transform('<ParentComponent title='Parent'><ChildComponent age='23'></ChildComponent></ParentComponent>).code); 
+0

Thanks for Reply @Shubham,但如果你會注意到我的字符串被雙引號括住,而你沒有。它的數據類型是字符串,因此在呈現其不處理反應組件時。 – Kracki

+0

準確地說,我不需要在雙引號內圍繞字符串,直接將JSX內容分配給變量 –

+0

我沒有任何其他選項,這是從後端獲取json的內容。如果我可以刪除UI上的引號或其他任何方式從String加載組件將會有所幫助。 – Kracki

0

感謝你能做到這一點。 庫'react-jsx-parser'解決了我的問題。