2016-10-17 61 views
0

好的我試圖傳遞一個組件作爲參數傳遞給我觸發的動作。在React組件內渲染一個React元素

this.context.alt.actions.notificationActions.logMessage({ 
    component: <ModalLayoutEditorComments subscription="pop-up" contextualClass="info" callback={this._submitCaisseChangeAction} />, 
    subscription: 'pop-up', 
}); 

在目標組件中,我接收對象作爲具有現在是React Element的組件的道具。

React element inside object

現在我想知道我怎麼可以把這個陣營內的另一個元素如果可能的話作出反應成分?

render() { 
     const Component = this.props.notifications[0].component; 

     return (
     <div> 
      {Component} 
     </div> 
    ); 
    } 
+0

你的'render'方法看起來不錯 - 這裏是渲染一個作爲道具傳遞的元素的示例:https://jsfiddle.net/txqo702m/1/ – joews

+0

在另一個React組件內使用ReactDOM.render是好的嗎?我嘗試使用React.cloneElement,但沒有運氣。 – Gab

+0

你不是在組件內調用'ReactDOM.render'?組件'render'方法構建一個React元素樹,最終通過應用程序根部的'ReactDOM.render'變成DOM元素樹。 – joews

回答

0

我得到的錯誤是以下

元素類型無效:預期字符串(內置組件) 或類/功能(複合組件),但得到:未定義

我得到了undefined,因爲我犯的錯誤是我沒有使用export default ModalLayoutEditorComments導出組件。

0

您的render邏輯正常。它看起來像你使用了錯誤的道具:

render() {  
    return (
    <div> 
     {this.props.notifications[0].component} 
    </div> 
); 
} 

順便說一句,component是一個相當混亂的屬性名稱。該對象是一個React元素,它是一個description of a Component instance

+0

對不起,它不起作用 – Gab

+0

你需要更具體嗎?什麼是錯誤?渲染元素作爲道具傳遞是一種常見的React模式(例如'{children}')。 https://jsfiddle.net/txqo702m/1/是否適合你? – joews

+0

抱歉,因爲我得到了undefined,所以我犯的錯誤是我沒有使用導出默認的ModalLayoutEditorComments導出組件。 – Gab