React Native,TypeError:undefined不是对象,当我使用onPress函数时



我正在尝试调用 like_click(( 的可触摸不透明度的 onPress,但它给了我一个错误(未定义不是一个对象(。

我也尝试用这个调用该方法,但它也给了我一个错误(找不到变量like_click(

constructor(props){
super(props)
this.logout = this.logout.bind(this);
this.state = {
username:"",
password:"",
token:"",
firstName:"",
dataSource:""
}
**this.like_click = this.like_click.bind(this);**
this.dislike_click = this.dislike_click.bind(this);
this.workjoyPage = this.workjoyPage.bind(this);
}

**like_click(expr_id){
console.log(this.state.token);
console.log(expr_id);
var headers = new Headers();
let auth ='Bearer '+this.state.token;
headers.append("Authorization",auth);        
fetch("http://diwo.nu/public/api/addExpLikes/"+expr_id, {
method: 'GET',        
headers: headers,
})
.then((response) => response.json())
.then((responseJson) => {
if(responseJson.status==200){
console.log(responseJson);
this.componentDidMount();
}
}).catch((error) =>{
console.error(error);
});
}**

_renderItem ({item, index}) {
var {height, width} = Dimensions.get('window');
return (
<View style={styles.dynamic_list_view}>                    
<Card borderRadius={15} containerStyle={{marginLeft:12,backgroundColor:'#00a1ff'}}>
<View style={{paddingRight:10}}>
{item.user_likes==0?
**<TouchableOpacity onPress={()=>this.like_click(item.id)}>
<Image style={{width:20, height:20,marginTop:10,marginRight:5}} source={require('../../uploads/heart1.png')} />
</TouchableOpacity>**
:
<TouchableOpacity onPress={()=>dislike_click(item.id)}>
</TouchableOpacity>}                           
</View>
</Card>
</View>
);
}
render() {
<View style={{flex:2.2}}>
<Carousel
ref={(c) => { this._carousel = c; }}
data={this.state.dataSource}
**renderItem={this._renderItem}**
sliderWidth={350}
itemWidth={350}
autoplay={true}
autoplayDelay={2000}
loop={true}
/>
</View>
}

单击图像时,我应该如何调用函数。请帮忙。

尝试使用es6 fat箭头函数,因为它使代码更容易,所以你不必显式绑定它。

like_click = (expr_id) =>{
console.log(this.state.token);
console.log(expr_id);
var headers = new Headers();
let auth ='Bearer '+this.state.token;
headers.append("Authorization",auth);        
fetch("http://diwo.nu/public/api/addExpLikes/"+expr_id, {
method: 'GET',        
headers: headers,
})
.then((response) => response.json())
.then((responseJson) => {
if(responseJson.status==200){
console.log(responseJson);
this.componentDidMount();
}
}).catch((error) =>{
console.error(error);
});
}**

并在您的可触摸不透明度调用中,例如

<TouchableOpacity onPress={()=>this.like_click(item.id)}>

在like_click可以尝试控制台.log检查是否调用了该函数。如果调用它,则意味着您的like_click func API 调用中存在错误。一定要检查一下。

最新更新