如何根据React中的javascript对象渲染组件X次? [英] How can I render a component X amount of times based on a javascript object in React?
本文介绍了如何根据React中的javascript对象渲染组件X次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试渲染X张照片,具体取决于 OBJECT(照片)
的时长。我试过将数据附加到字符串但它不起作用。有什么好的解决方案吗?
I'm trying to render an X amount of photos depending on how long the OBJECT (photos)
is. I've tried just appending data to a string but it doesn't work. Any good solutions?
var RenderPhotos = React.createClass({
getInitialState: function() {
return {
photos: this.props.photos
};
},
render: function(){
var photoHolder = "";
for(var i=0;i<this.props.photos.length;i++){
photoHolder += ("<View>
<Text>" { this.props.photos[0].description } "</Text>
</View>");
}
return (
{ photoHolder }
// <View>
// <Text> { this.props.photos[0].description } </Text>
// </View>
)
}
});
推荐答案
更新2017年12月:React v16现在允许您返回来自 render
函数的数组。
UPDATE December 2017: React v16 now allows you to return an array from the render
function.
使用React类,您的顶级渲染
函数必须返回单个组件。但是,在JSX中,您可以插入单个组件或组件数组。
With a React class, your top-level render
function MUST return a single component. However, inside your JSX, you can insert a single component, OR an array of components.
如下所示:
render() {
var photoHolder = [];
for(var i=0;i<this.props.photos.length;i++){
photoHolder.push(
(<View>
<Text>{ this.props.photos[0].description }</Text>
</View>)
);
}
return (
<View>
{photoHolder}
</View>
)
}
编辑:这是另一个解决方案:
Here's another solution:
render() {
return (
<View>
{this.props.photos.map((photo, i) => {
return (
<View><Text>{photo.description}</Text></View>
);
})}
</View>
)
}
这篇关于如何根据React中的javascript对象渲染组件X次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文