如何根据React中的javascript对象渲染组件X次?
发布时间:2020-12-15 16:17:52 所属栏目:百科 来源:网络整理
导读:我试图根据OBJECT(照片)的长度渲染X张照片.我试过将数据附加到字符串但它不起作用.好的解决方案? var RenderPhotos = React.createClass({ getInitialState: function() { return { photos: this.props.photos }; },render: function(){ var photoHolder =
我试图根据OBJECT(照片)的长度渲染X张照片.我试过将数据附加到字符串但它不起作用.好的解决方案?
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> ) } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |