For loop in react render method

This question already has an answer here:

  • Loop inside React JSX 38 answers
  • for loop in react 1 answer

  • You can run the loop before the rendering (note that there's an error in your for loop)

    var lis = [];
    
    for (var i=0; i<10; i++) {
        lis.push(<li><a href="#">{i + 1}</a></li>);
    }
    
    var Pagination = React.createClass({
        render: function(){
            return(
                <div class="text-center">
                    <ul class="pagination">
    
                        <li><a href="#">«</a></li>
                        {lis}
                        <li><a href="#">»</a></li>
                    </ul>
                </div>
            );
        }
    });
    

    FIDDLE


    You can only embed expressions into JSX.

    <ul className="pagination">{children}</ul>
    

    is converted to something like

    React.createElement('ul', {className: 'pagination'}, children);
    

    Do you see now how you could never have a for loop in place of children ? Statements cannot be inside a function call expression.

    You can create an array beforehand, like adeneo showed in their answer.

    链接地址: http://www.djcxy.com/p/52040.html

    上一篇: 我如何使用循环与反应?

    下一篇: 用于循环中的反应渲染方法