首页 > 解决方案 > 如何在 React Native 的 .map 中调用类函数

问题描述

我将在模板中调用类的函数。这就是我所做的。

class recommendFeedback extends Component<{}>{
    starImgFromRating(tip) { // this function should be called but not.
    // ... 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>
                    })
                }
            </View>
        )
    }
}

但是效果不好。

标签: arraysreactjsreact-native

解决方案


应该是source = {this.starImgFromRating(item)}因为您需要starImgFromRating在渲染期间评估Thumbnail要使用的组件的结果。

将函数作为 prop 值传递通常用于事件处理程序。

您还应该将箭头函数用于map:.map((item) => {以避免绑定this到该函数。


推荐阅读