2016-07-27 86 views
1

我有一個包含React Component字符串名稱(「SampleWidget1」)的數組;它由一個外部機制填充。在我的DashboardInterface組件中,我想要使用該數組,在其中呈現組件,並將其顯示在DashboardInterface.render函數中的其他靜態定義的HTML中。我如何在React中做到這一點?按字符串名稱動態實例化子組件 - ReactJs

以下是我的嘗試;沒有錯誤,但渲染的組件從未實際成功插入到DOM中。如果手動將SampleWidget1添加到DashboardInterface.render函數()中,它將按預期方式顯示。如果我對動態渲染的組件做同樣的事情,它不會出現。

有什麼建議嗎?

var widgetsToRender = ["SampleWidget1"]; 

/** 
* Dashboard that uses Gridster.js to display widget components 
*/ 
var DashboardInterface = React.createClass({ 

    /** 
    * Loads components within array by their name 
    */ 
    renderArticles: function(widgets) { 

     if (widgets.length > 0) { 

      var compiledWidgets = []; 

      // Iterate the array of widgets, render them, and return compiled array 
      for(var i=0; i<widgets.length; i++){ 
       compiledWidgets.push(React.createElement(widgets[i] , {key: i})); 
      } 

      return compiledWidgets; 

     } 
     else return []; 
    }, 

    /** 
    * Load the jQuery Gridster library 
    */ 
    componentDidMount: function(){ 

     // Initialize jQuery Gridster library 
     $(".gridsterDashboard ul").gridster({ 
      widget_margins: [10, 10], 
      widget_base_dimensions: [140, 140], 
      //shift_larger_widgets_down: false 
     }); 

    }, 

    render: function() { 

     // Get the widgets to be loaded into the dashboard 
     var widgets = this.renderArticles(widgetsToRender); 

     return (
       <div className="gridsterDashboard"> 
        <ul > 
         {this.widgets} 
         <SampleWidget1 /> 
        </ul> 
       </div> 
     ); 
    } 

}); 

這裏是我試圖呈現一個樣本成分:

/** 
* Sample component that return list item that is to be insert into Gridster.js 
*/ 
var SampleWidget1 = React.createClass({ 

    render: function() { 

     // Data will be pulled here and added inside the list item... 

     return (
      <li data-row="1" data-col="1" data-sizex="2" data-sizey="1">testing fake component</li> 
     ) 

    } 

}); 



ReactDOM.render(
    <DashboardInterface />, 
    document.getElementById('dashboard') 
); 

回答

1

的,你應該導入組件,然後選擇所需,通過關鍵屬性

1)簡短的例子

import * as widgets from './widgets.js'; 

const widgetsToRender = ["Comp1","Comp2","Comp3"]; 

class App extends Component { 
    render(){ 
     const Widget = widgets[this.props.widgetsToRender[0]] 
     return <Widget /> 
    } 
} 

2)全部實施例 webpackbin DEMO


3)實施例具有多個組件

renderWidgets(selected){ 
    return selected.map(e=>{ 
     let Widget =widgets[this.props.widgetsToRender[e-1]]; 
     return <Widget key={e}/> 
    }) 
    } 

webpackbin DEMO

enter image description here

+0

感謝偉大的例子。我試圖在傳統JavaScript中編寫代碼,因爲我還沒有學過Es6和編譯工作流程。您是否熟悉在ES5中顯示等效設計的資源? – ph34r

+1

@ ph34r我可以在es5上重寫它。你想要哪一個例子?你使用模塊嗎?或者你只需​​要es5反應組件 –

+0

Utro,我真的很感謝你的幫助,你已經超越了。我一直試圖解決這個問題已經有好幾天了,所以ES5對你的第三個例子的翻譯將會非常有幫助。我一直試圖只使用ES5反應組件。 – ph34r