Javascript 如何在没有要映射的对象数组的情况下循环和渲染 React.js 中的元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29149169/
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
How to loop and render elements in React.js without an array of objects to map?
提问by Jonathan Miles
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. 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?
我知道这是不可能的,或推荐的,并且模型中存在数组的地方使用map. 那很好,但是当您没有数组时怎么办?相反,您有一个数值,它等于要呈现的给定数量的元素,那么您应该怎么做?
Here's my example, I want to prefix a element with an arbitrary number of span tags based on it's hierarchical level. 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. Instead I had to do the following, first building a temp array to the correct length and then looping the array.
我似乎无法得到这个,或者任何类似于在 JSX React.js 组件中工作的东西。相反,我必须执行以下操作,首先构建一个正确长度的临时数组,然后循环该数组。
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?
这肯定不是最好的,或者是实现这一目标的唯一方法?我错过了什么?
回答by Dhiraj
Updated: As of React > 0.16
更新:从 React > 0.16
Render method does not necessarily have to return a single element. An array can also be returned.
Render 方法不一定必须返回单个元素。也可以返回一个数组。
var indents = [];
for (var i = 0; i < this.props.level; i++) {
indents.push(<span className='indent' key={i}></span>);
}
return indents;
OR
或者
return this.props.level.map((item, index) => (
<span className="indent" key={index}>
{index}
</span>
));
Docs here explaining about JSX children
OLD:
老的:
You can use one loop instead
您可以改用一个循环
var indents = [];
for (var i = 0; i < this.props.level; i++) {
indents.push(<span className='indent' key={i}></span>);
}
return (
<div>
{indents}
"Some text value"
</div>
);
You can also use .mapand fancy es6
您还可以使用.map和花式 es6
return (
<div>
{this.props.level.map((item, index) => (
<span className='indent' key={index} />
))}
"Some text value"
</div>
);
Also, you have to wrap the return value in a container. I used div in the above example
此外,您必须将返回值包装在容器中。我在上面的例子中使用了 div
As the docs say here
正如文档在这里所说
Currently, in a component's render, you can only return one node; if you have, say, a list of divs to return, you must wrap your components within a div, span or any other component.
目前,在一个组件的渲染中,你只能返回一个节点;例如,如果您有一个要返回的 div 列表,则必须将组件包装在 div、span 或任何其他组件中。
回答by Dmytro Medvid
Here is more functional example with some ES6 features:
这是具有一些 ES6 特性的更多功能示例:
'use strict';
const React = require('react');
function renderArticles(articles) {
if (articles.length > 0) {
return articles.map((article, index) => (
<Article key={index} article={article} />
));
}
else return [];
}
const Article = ({article}) => {
return (
<article key={article.id}>
<a href={article.link}>{article.title}</a>
<p>{article.description}</p>
</article>
);
};
const Articles = React.createClass({
render() {
const articles = renderArticles(this.props.articles);
return (
<section>
{ articles }
</section>
);
}
});
module.exports = Articles;
回答by Mathdoy
I'm using Object.keys(chars).map(...)to loop in render
我正在使用Object.keys(chars).map(...)循环渲染
// chars = {a:true, b:false, ..., z:false}
render() {
return (
<div>
{chars && Object.keys(chars).map(function(char, idx) {
return <span key={idx}>{char}</span>;
}.bind(this))}
"Some text value"
</div>
);
}
回答by conradj
Array.from()takes an iterable object to convert to an array and an optional map function. You could create an object with a .lengthproperty as follows:
Array.from()接受一个可迭代对象转换为一个数组和一个可选的 map 函数。您可以创建一个具有.length属性的对象,如下所示:
return Array.from({length: this.props.level}, (item, index) =>
<span className="indent" key={index}></span>
);
回答by Nasar uddin
I think this is the easiest way to loop in react js
我认为这是在 react js 中循环的最简单方法
<ul>
{yourarray.map((item)=><li>{item}</li>)}
</ul>

