按字符串名称动态实例化子组件 - ReactJs

时间:2016-07-27 20:35:20

标签: javascript reactjs react-jsx

我有一个包含React Component字符串名称的数组(“SampleWidget1”);它由外部机制组成。在我的DashboardInterface组件中,我想使用该数组,呈现其中包含的组件,并在DashboardInterface.render函数中的其他静态定义的HTML中显示它。我怎么能在React中做到这一点?

以下是我的尝试;没有错误,但渲染的组件实际上从未成功插入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 个答案:

答案 0 :(得分:2)

为此您应该导入组件并按键属性

选择所需的组件

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