在React JSX内部循环

本文翻译自:Loop inside React JSX

I'm trying to do something like the following in React JSX (where ObjectRow is a separate component): 我正在React JSX尝试执行以下操作(其中ObjectRow是一个单独的组件):

<tbody>
    for (var i=0; i < numrows; i++) {
        <ObjectRow/>
    } 
</tbody>

I realize and understand why this isn't valid JSX , since JSX maps to function calls. 我意识到并理解为什么这不是有效的JSX ,因为JSX映射到函数调用。 However, coming from template land and being new to JSX , I am unsure how I would achieve the above (adding a component multiple times). 但是,由于来自模板领域并且是JSX新手,所以我不确定如何实现上述目标(多次添加组件)。


#1楼

参考:https://stackoom.com/question/1XzLW/在React-JSX内部循环


#2楼

Think of it like you're just calling JavaScript functions. 就像您只是在调用JavaScript函数一样。 You can't use a for loop where the arguments to a function call would go: 您不能在for循环中使用函数调用的参数:

return tbody(
    for (var i = 0; i < numrows; i++) {
        ObjectRow()
    } 
)

See how the function tbody is being passed a for loop as an argument, and of course that's a syntax error. 了解如何将函数tbody作为参数传递给for循环,这当然是语法错误。

But you can make an array, and then pass that in as an argument: 但是您可以创建一个数组,然后将其作为参数传递:

var rows = [];
for (var i = 0; i < numrows; i++) {
    rows.push(ObjectRow());
}
return tbody(rows);

You can use basically the same structure when working with JSX: 使用JSX时,可以使用基本相同的结构:

var rows = [];
for (var i = 0; i < numrows; i++) {
    // note: we add 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值