如何动态声明组件

时间:2015-09-23 15:42:19

标签: reactjs react-jsx

使用:

this.props.components = [{component: input}, {component: button}]

在此代码中:

    var React = require('react');

var form = React.createClass({
    render: function () {
        var components = [];
        var component = null;
        //console.log(this.props.components);
        for (var i=0; i < this.props.components.length; i++) {
            console.log(this.props.components[i]);
            component = this.props.components[i].component;
            components.push(<component />);
        }
        console.log(components);
        return (
            <div>
                {components}
            </div>
        );
    }
});

module.exports = form;

我的问题是,它不是渲染包含输入和按钮的div,而是渲染两个类型为“component”的void元素。 有什么想法吗?

1 个答案:

答案 0 :(得分:1)

如果您已将组件传递到form类,请执行以下操作:

<Form
    components={[
        {component: <input />},
        {component: <button></button>}]}
/>

然后您不需要像这样在JSX中包装<component />,因为您已经渲染了组件。只是做:

for (var i = 0; i < this.props.components.length; i++) {
    component = this.props.components[i].component;
    components.push(component);
}