使用循环结构向React渲染调用添加道具

时间:2016-03-14 10:07:32

标签: reactjs react-jsx

假设我有一个数组(" props")我想用它渲染一个React组件。类似的东西:

const props = [];

ReactDOM.render(<Comp prop0={props[0]} prop1={props[1]/>, document.getElementById('foo'));

使用某种循环结构而不是&#34;硬编码&#34;是否有可行的方法将道具添加到React组件中它?

2 个答案:

答案 0 :(得分:4)

通常,你会在那里使用点差运算符:

var props = {};
props.foo = 'something';
props.bar = 'something else';

ReactDOM.render(<Component {...props} />, someDomElement);

答案 1 :(得分:0)

我想如果你想要使用可变数量的道具渲染可变数量的孩子,你可以这样做:

const React = require('react');


module.exports =  function(children){

    return React.createClass({

        renderChildren: function(){

            return children.map(function(Child){

                  return (
                      <div>
                          <Child {...Child.propz}/>
                      </div>
                  )
            });

        },

        render: function(){

            return (

                <html lang="en">
                <head>
                    <meta charset="UTF-8"></meta>
                    <title>Title</title>
                </head>
                <body>

                <div>
                    {this.renderChildren()}
                </div>

                </body>
                </html>

            )

        }

    });
};