我试图根据OBJECT(照片)的长度渲染X张照片.我试过将数据附加到字符串但它不起作用.好的解决方案? var RenderPhotos = React.createClass({ getInitialState: function() { return { photos: this.props.photos }; }
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现在允许您从渲染功能返回一个数组.
使用React类,顶级渲染函数必须返回单个组件.但是,在JSX中,您可以插入单个组件或组件数组.
像这样:
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>
)
}
编辑:这是另一种解决方案:
render() {
return (
<View>
{this.props.photos.map((photo, i) => {
return (
<View><Text>{photo.description}</Text></View>
);
})}
</View>
)
}
