【问题标题】:Dynamic Instantiation of Child Components by String name - ReactJs通过字符串名称动态实例化子组件 - ReactJs
【发布时间】:2016-07-27 20:35:20
【问题描述】:

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

【问题讨论】:

    标签: javascript reactjs react-jsx


    【解决方案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 演示


    3 ) 包含多个组件的示例

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

    webpackbin DEMO

    【讨论】:

    • 感谢您提供的出色示例。由于我还没有学习 Es6 和编译工作流程,因此我试图在旧版 JavaScript 中对此进行编码。您是否熟悉任何在 ES5 中显示等效设计的资源?
    • @ph34r 我可以在 es5 上重写它。你想要哪一个例子。你使用模块吗?或者你只需​​要 es5 react 组件
    • Utro,我真的很感谢你的帮助,你已经超越了。几天来,我一直在努力解决这个问题,因此您的第三个示例的 ES5 版本将非常有帮助。我一直在尝试只使用 ES5 react 组件。
    • 这太棒了,正是我想要弄清楚的——非常感谢!看来我是在正确的轨道上。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 2014-06-04
    相关资源
    最近更新 更多