Javascript 反应渲染方法中的for循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29859380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:08:35  来源:igfitidea点击:

For loop in react render method

javascriptreactjs

提问by user1924375

I want create paging link for my grid.I pass maxPages(number) property to component but i cant use for in render method. What can i do ?

我想为我的网格创建分页链接。我将 maxPages(number) 属性传递给组件,但我不能在渲染方法中使用。我能做什么 ?

var Pagination = React.createClass({

render: function(){


    return(
    <div class="text-center">
        <ul class="pagination">

            <li><a href="#">?</a></li>
            {for (var i=0;i <10;i++;)
            {
              return( <li><a href="#">i + 1 </a></li>);
            }
            }

            <li><a href="#">?</a></li>
        </ul>
    </div>);

}});

采纳答案by adeneo

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

您可以在渲染之前运行循环(注意循环中有错误for

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

小提琴

回答by Felix Kling

You can only embed expressions into JSX.

您只能将表达式嵌入到 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 forloop in place of children? Statements cannot be inside a function call expression.

你现在看到你怎么可能永远不会有一个for循环来代替children吗?语句不能在函数调用表达式中。

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

您可以预先创建一个数组,就像他们的 answer 中显示的 adeneo一样。