我正在try 将jQuery组件转换为react js,我遇到的困难之一是基于for循环呈现n个元素.
I understand this is not possible, or recommended and that where an array exists in the model it makes complete sense to use map
. That's fine, but what about when you do not have an array? Instead you have numeric value which equates to a given number of elements to render, then what should you do?
下面是我的示例,我想根据元素的层次 struct 级别为其添加任意数量的span标记作为前缀.因此,在级别3,我希望文本元素之前有3个跨距标记.
在javascript中:
for (var i = 0; i < level; i++) {
$el.append('<span class="indent"></span>');
}
$el.append('Some text value');
我似乎无法理解这一点,或者任何类似于在JSX react js组件中工作的内容.相反,我必须执行以下操作,首先构建一个长度正确的临时数组,然后循环该array.
react js
render: function() {
var tmp = [];
for (var i = 0; i < this.props.level; i++) {
tmp.push(i);
}
var indents = tmp.map(function (i) {
return (
<span className='indent'></span>
);
});
return (
...
{indents}
"Some text value"
...
);
}
Surely this can't be the best, or only way to achieve this? What am I missing?