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

Dynamic Instantiation of Child Components by String name - ReactJs

我有一个包含 React 组件字符串名称的数组 ("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')
);

为此,您应该导入组件和 select 所需的按键 属性

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 演示


3 ) 具有多个组件的示例

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

webpackbin DEMO