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

IT技术 javascript reactjs react-jsx
2021-04-25 00:01:14

我有一个包含 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')
);
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 演示

在此处输入图片说明