React Native中如何在.map方法里调用类组件的函数?
问题分析与解决方法
你的代码无法正常工作,核心问题有两个:
this指向错误:在map的普通函数回调里,this并没有指向组件实例,导致无法调用starImgFromRating方法。source属性赋值错误:你给Thumbnail的source传了一个函数,而不是直接传入starImgFromRating返回的图片资源结果。
下面是几种可行的修复方案:
方案1:使用箭头函数作为map回调(最推荐)
箭头函数不会绑定自己的this,会继承外层作用域的this(也就是当前组件实例),同时直接调用方法获取图片资源:
class recommendFeedback extends Component<{}>{ starImgFromRating(tip) { // ... some operation with tip. return result } render(){ return( <View style = {styles.container}> { this.props.venue.tips.map((item) => { return <View> <Thumbnail source={this.starImgFromRating(item)} /> </View> }) } </View> ) } }
方案2:给普通函数回调绑定this
如果坚持使用普通函数,可以通过bind(this)手动将回调的this绑定到组件实例:
class recommendFeedback extends Component<{}>{ starImgFromRating(tip) { // ... some operation with tip. return result } render(){ return( <View style = {styles.container}> { this.props.venue.tips.map(function(item) { return <View> <Thumbnail source={this.starImgFromRating(item)} /> </View> }.bind(this)) } </View> ) } }
方案3:提前保存this到变量
在render方法开头把组件实例的this存到一个变量(比如that),在回调里用这个变量访问方法:
class recommendFeedback extends Component<{}>{ starImgFromRating(tip) { // ... some operation with tip. return result } render(){ const that = this; return( <View style = {styles.container}> { this.props.venue.tips.map(function(item) { return <View> <Thumbnail source={that.starImgFromRating(item)} /> </View> }) } </View> ) } }
记得确保starImgFromRating方法返回的是符合Thumbnail组件source要求的格式(比如require('./path/to/image.png')或者{ uri: 'image-url' }),这样图片才能正常显示。
内容的提问来源于stack exchange,提问作者Nomura Nori
相关产品推荐
相关产品推荐

