I'm trying to convert a jQuery component to React.js and one of the things I'm having difficulty with is rendering n number of elements based on a for loop.
(我正在尝试将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
.
(我理解这是不可能的,或者推荐并且如果模型中存在数组,那么使用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?(相反,你有数值等于要渲染的给定数量的元素,那么你应该怎么做?)
Here's my example, I want to prefix a element with an arbitrary number of span tags based on it's hierarchical level.
(这是我的例子,我想根据它的层次级别为一个元素添加任意数量的span标记。)
So at level 3, I want 3 span tags before the text element.(所以在第3级,我想在文本元素之前使用3个span标签。)
In javascript:
(在javascript中:)
for (var i = 0; i < level; i++) {
$el.append('<span class="indent"></span>');
}
$el.append('Some text value');
I can't seem to get this, or anything similar to work in a JSX React.js component.
(我似乎无法得到这个,或类似的东西在JSX React.js组件中工作。)
Instead I had to do the following, first building a temp array to the correct length and then looping the array.(相反,我必须执行以下操作,首先将temp数组构建为正确的长度然后循环数组。)
React.js
(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?(我错过了什么?)
ask by Jonathan Miles translate from so
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…