【发布时间】:2019-07-13 22:55:19
【问题描述】:
我有一个滚动视图,其中多个项目是通过循环生成的。我在这些项目上方添加了 TouchableOpacity,因为我希望这些对象是可触摸的。但是当我在 onPress 方法上添加一个方法时,它显示错误 not a function , is undefined
List_Data 组件:
class List_Data extends React.Component {
fetchData = () => {
console.log("DONE");
}
_renderView = () => {
return (
<View style={{flex:1, padding: 20}}>
<View style={styles.container}>
<ScrollView horizontal={true} showsHorizontalScrollIndicator={false} >
{
this.state.Data.map(function (data, index) {
return (
<TouchableOpacity key={index} onPress={() => this.fetchData()}>
<Image source={{uri: data.imageSrc}}
resizeMode={'cover'}
style={{width: '100%', height: imageHeight}}
/>
</TouchableOpacity>
);
})
}
</ScrollView>
</View>
</View>
)
}
render() {
return (
{this._renderView()}
);
}
}
我不知道是什么问题,它只是一种在控制台上打印的方法。
【问题讨论】:
-
将
this.state.Data.map(function (data, index) {更改为this.state.Data.map((data, index) => {。您的问题是this的上下文不是您所期望的。当您使用箭头函数时,this的上下文是词法范围的。 -
还是同样的问题...
-
你试过
this.fetchData.bind(this)吗?
标签: reactjs typescript react-native ecmascript-6