按字符串名称动态实例化子组件 - ReactJs [英] Dynamic Instantiation of Child Components by String name - ReactJs

查看:117
本文介绍了按字符串名称动态实例化子组件 - ReactJs的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



以下是我的尝试;没有错误,但渲染的组件实际上从未成功插入DOM。如果我手动将SampleWidget1添加到DashboardInterface.render函数()中,它将按预期显示。如果我对动态渲染的组件做同样的事情,它就不会出现。



有什么建议吗?

  var widgetsToRender = [SampleWidget1]; 

/ **
*使用Gridster.js显示小部件组件的仪表板
* /
var DashboardInterface = React.createClass({

/ **
*按名称加载数组中的组件
* /
renderArticles:function(widgets){

if(widgets.length> 0 ){

var compiledWidgets = [];

//迭代小部件数组,渲染它们,并返回编译后的数组
for(var i = 0; i< widgets.length; i ++){
compiledWidgets.push(React.createElement(widgets [i],{key:i}));
}

返回compiledWidgets;

}
else return [];
},

/ **
*加载jQuery Gridster库
* /
componentDidMount:function(){

//初始化jQuery Gridster库
$(。gridsterDashboard ul)。gridster({
widget_margins:[1 0,10],
widget_base_dimensions:[140,140],
// shift_larger_widgets_down:false
});

},

渲染:function(){

//获取要加载到仪表板的小部件
var widgets = this.renderArticles(widgetsToRender);

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

});

这是我要渲染的示例组件:

  / ** 
*返回要插入Gridster.js的列表项的示例组件
* /
var SampleWidget1 = React.createClass({

render:function(){

//数据将被拉到此处并添加到列表项中...

返回(
< li data-row =1data-col =1data-sizex =2data-sizey =1>测试假组件< / li>


}

});



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


解决方案

为此您应该导入组件并选择所需的,关键属性



1)简短示例

 从* ./widgets.js导入*作为小部件; 

const widgetsToRender = [Comp1,Comp2,Comp3];

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

2)完整示例
webpackbin DEMO






3)包含多个组件的示例

  renderWidgets(已选中){
return selected.map(e => {
let Widget =小部件[this.props.widgetsToRender [e-1]];
返回< Widget键= {e} />
})
}


I have an array that contains React Component string names ("SampleWidget1"); it's populated by an external mechanism. Within my DashboardInterface component, I'd like to consume that array, render the Components contained within it, and display it amongst other statically defined HTML in the DashboardInterface.render function. How can I do this in React?

Below is my attempt; there are no errors, but the rendered components are never actually successfully inserted into the DOM. If I manually add the SampleWidget1 into the DashboardInterface.render function () it displays as expected. If I do the same with the dynamically rendered component, it does not appear.

Any suggestions?

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>
        );
    }

});

Here is a sample component that I'm trying to render:

/**
 * 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')
);

解决方案

for that you should import components and select desired, by key property

1 ) short example

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 ) Full example webpackbin DEMO


3 ) Example with multiple components

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

webpackbin DEMO

这篇关于按字符串名称动态实例化子组件 - ReactJs的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆